Preference checkbox and BroadcastReceiver how to? - Java for Android App Development

my battery application has a settings menu in wich there are basically 3 checkbox. In the first (the main, until this is uncheked the others are not clickable) there is the option to activate the nofications in the navigation bar. In the others it's possible to choose what show in the notification. Now the xml of the preference.
Code:
<PreferenceCategory
android:summary="Settings"
android:title="Settings" >
<CheckBoxPreference
android:defaultValue="true"
android:key="first"
android:summary="@string/summary_show"
android:title="@string/Show_notifications" />
<CheckBoxPreference
android:defaultValue="false"
android:dependency="first"
android:key="second"
android:summary="@string/summary_level"
android:title="@string/title_battery_level" />
<CheckBoxPreference
android:defaultValue="false"
android:dependency="first"
android:key="third"
android:summary="@string/summary_temp"
android:title="@string/title_temperature" />
</PreferenceCategory>
Now, in my ActivityMain i have the code to show the informations about the battery through the BroadcastReceiver(i write only for the battery level because i think the other is the same):
Code:
private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
[user=439709]@override[/user]
public void onReceive(Context context, Intent intent) {
int level= intent.getIntExtra(BatteryManager.EXTRA_LEVEL,-1);
. . .
String[] statusbatt = {
"Battery level: " +level+"%",
. . .};
ListView lvStatus = (ListView) findViewById(R.id.lv_status);
lvStatus.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.list, statusbatt));
info.getListViewSize(lvStatus);
}
};
And the last thing is the notification's code:
Code:
NotificationManager notifi = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification.Builder(getApplicationContext())
.setContentTitle("Battery Informations")
.setContentText("Batteria al"+" "+level+"%")
.setSmallIcon(R.drawable.icon_small_not)
.setTicker(level+"%")
.build();
notification.flags = Notification.FLAG_ONGOING_EVENT;
Intent i = new Intent(context, MainActivity.class);
PendingIntent penInt = PendingIntent.getActivity(getApplicationContext(), 0 , i , 0);
notifi.notify(215,notification);
Actually the notification start when launch the application and i can't turn it off and it's because i need to make the settings to check and choose if display it or not. What i want is that in a new activity, settings.java, when i press the first check box i can activate the notifications and then, by what you decide, the notifications appears. I mean, i check the first (the notifications are now avaible), i choose to display the battery level in the notification and the temperature so now they added in the notification. Hope you understand. thanks

Any help?

What help you need the Batter Stats part or CheckBox part
Sent from my GT-S5302 using Tapatalk 2

Related

Click on Notification does not work as expected... (see screencast!):(

Hi guys,
first of all - Merry Christmas!!!
I have a strange problem here and spent too many hours figuring out what the problem might be. I definitely need your help here now... I'm pretty sure this is very easy to fix... if you know how...
I develop a little free app for German O2 customers so that they can send their 50 free Web-SMS directly from their Android phone and not only via web interface like O2 wants them to. These SMS are sent in the background using a service. This service generates notifications (e.g. Message sent successfully, Login successful/failed,...)
When I click on that notification the app should open and then display the notification message. This works pretty fine as long as the app is visible (foreground/active). When putting the app into the background it's getting launched as well, but it doesn't display the message... then, when I hold down the HOME-Key and select the app... the message gets displayed.
See the following video... to show you what I mean...
http://dl.dropbox.com/u/1676562/NotificationIssue.mov
I'm pretty sure it has something to do with the Fflags for my intent, so here's my code:
Setting the notification:
Code:
// The PendingIntent to launch our activity if the user selects this
// notification
final Intent notificationIntent = new Intent(ManagerFactory
.getMasterActivity(), MailerActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
Log.d(TAG, "Set new message to Notification: " + p_message);
notificationIntent
.putExtra(Constants.NOTIFICATION_EXTRA_KEY, p_message);
Log.d(TAG, "Setting requestCodeToFixNotificationBug: "
+ s_requestCodeToFixNotificationBug);
final PendingIntent contentIntent = PendingIntent.getActivity(
ManagerFactory.s_service, s_requestCodeToFixNotificationBug++,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(ManagerFactory.s_service, p_tickerText,
p_message, contentIntent);
Reacting on the incoming intent:
Code:
/*
* (non-Javadoc)
*
* @see android.app.Activity#onNewIntent(android.content.Intent)
*/
@Override
protected final void onNewIntent(final Intent p_intent) {
// when called via notification, get the extras
Log.d(TAG, "Called onNewIntent...");
final Bundle extras = p_intent.getExtras();
Log.d(TAG, "Extra: " + extras);
if (extras != null
&& extras.getString(Constants.NOTIFICATION_EXTRA_KEY) != null
&& !extras.getString(Constants.NOTIFICATION_EXTRA_KEY).trim()
.equalsIgnoreCase("")) {
Log.d(TAG, "Extra:"
+ extras.getString(Constants.NOTIFICATION_EXTRA_KEY));
this.showLongMessage(extras
.getString(Constants.NOTIFICATION_EXTRA_KEY));
}
}
Would be great if someone was able to help me...
Sascha
Does onNewIntent get called? If it does, try stepping through the code with a debugger. Also try setting a unique value to the Intent's data field like System.currentTimeMillis().
Doing this fixed a similar issue for me.

AppWidget problem when process is running

So I'm programming a application with a widget.
On my widget I got a button that starts an activity with a PendingIntent. This activity that's getting launched isn't my main activity.
Now when I'm doing it like this I get a Strange problem:
- Launching App as normal over appdrawer -> main activity opens up
- Pressing Home or Back button
- Add widget to homescreen
- Click button on widget -> nothing happens!
If I force stop my application before adding the widget to the homescreen, a click on the button on the widget opens up the activity like it should. Now I can also launch my main activity, pause it and the widget still works. So the widget only fully works if I my application isn't running in the background while adding the widget.
Has anyone of you experienced something like that?
Thank you in advance!
it is really dependent on how your onClickListener is added to the button. ive had problems where the first widget i create doesnt have the onClickListener attached but the second one will. do you mind sharing your code that you use to attach the onClickListener?
here is mine:
Code:
/** Called when the activity is first created. */
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Toast.makeText(context, "onUpdate()", Toast.LENGTH_SHORT).show();
//super.onUpdate(context, appWidgetManager, appWidgetIds);
//attach an onClick intent to the layout
final Intent onClick = new Intent(context, GITextCloud.class);
onClick.setAction(LAUNCH_GMAIL_GAPPS);
PendingIntent onClickPending = PendingIntent.getBroadcast(context, 0, onClick, 0);
RemoteViews rv1 = new RemoteViews(context.getPackageName(), R.layout.gitc_html);
rv1.setOnClickPendingIntent(R.id.full_widget, onClickPending);
for (int appWidgetId : appWidgetIds) {
appWidgetManager.updateAppWidget(appWidgetId, rv1);
}
}
My code is really almost the same. Just that I need PendingIntent.getActivity instead of getBroadcast.
what flags do you set for your intent? cause if your activity is already running and thats when the button wont work it could be that you need a Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT or some other flags in the PendingIntent
try setting onClick.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) or what ever your Intent is called. i think the fact that your widget and your app are going to be seperate programs means they must start in different threads. cause not all widgets need an Activity running to function
I got it now! I somehow managed to screw up my remoteviews, they didn't got updated properly.
Anyway, thanks a lot for your answers

[Q] Making an alternatice UI menu (like for example: the camera menu)

I am trying to create a more appealing menu for my application, however I am unsure as how to re-root the input of the menu button so that it makes certain images in the corners visible, (they are all in the same xml file, however just set to "invisible" by default. If also possible I'd like to activate this menu by just touching the screen, does anyone have any advice on how to do this?
If you need any more information please just ask
Thank you
You'll need to capture the menu button click. This might help:
http://stackoverflow.com/questions/4239880/detecting-physical-menu-key-press-in-android
For touching the screen you'll need an onTouch event for the view.
Sent from my HTC Desire using XDA App
thanks
but i am still unsure as how to identify the xml object and then change it's visibility in java
image:
Code:
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/menu_bottom_left"
android:id="@+id/bl"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:visibility="invisible"></ImageView>
using the physical keycode:
Code:
public boolean onKeyUp(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_MENU)
{
}
return true;
}
sorry but i am not that familiar with java
OK.
// Create an ImageView and assign it to your bl ImageView
Imageview bl= (ImageView)findViewById(R.id.bl);
// Change the visibility (VISIBLE = Visible, INVISIBLE = Invisible but takes up the same space in layout
// GONE = Invisible and does not take up space in layout)
bl.setVisibility(ImageView.VISIBLE);
Hope this helps

[Q] How to keep layouts inflated after activity restarts

Hi guys,
On a button click I am inflating a layout like so:
Code:
public void plusLayout(View v) {
// inflating layout here:
LinearLayout ll1 = (LinearLayout) findViewById(R.id.main_layout);
// this layout is being inflated:
View newView = getLayoutInflater().inflate(R.layout.layout_to_be_added, null);
// add layout
ll1.addView(newView);
}
But when the activity restarts, the inflated layouts are gone.
I'd like the layouts to stay there.
(The user can click a button to remove the layout by hand).
I must be missing something trivial here right?
Cheers,
Daan
Which way is it restarted?
If the complete app is restarted, a new layout will be set in the onCreate method.
nikwen said:
Which way is it restarted?
If the complete app is restarted, a new layout will be set in the onCreate method.
Click to expand...
Click to collapse
Yeah when you press back button and start the app again or completely kill it.
It also happens on orientation change as the activity get restarted then as well.
But I think you can override that in the manifest somewhere.
DaanJordaan said:
Yeah when you press back button and start the app again or completely kill it.
It also happens on orientation change as the activity get restarted then as well.
But I think you can override that in the manifest somewhere.
Click to expand...
Click to collapse
Ah ok.
The point is: If you open the app or turn your device, the onCreate method is called. There you set a completely new layout. You would need to save that the layout is inflated (you could use a SharedPreferences entry) and inflate it in the onCreate method. If you just want it to appear again after turning the device, use the onSaveInstanceState method and the onRestoreInstanceState method. That would be better practice.
Look at the activity lifecycle.
Just so I'm sure I get this right :
The user launches the app, the layouts are not inflated
He presses a button which calls your plusLayout() method, so the layouts are now inflated
The user quits the activity and restarts it, the layouts are not inflated anymore but you want them to.
Is that correct ?
If it is, 2 ways I can think of :
Overriding savedInstanceState() & onRestoreInstanceState() :
First, declare a private Boolean before the onCreate() of your activity :
Code:
private Boolean isInflated = false;
Then, set it to true in the onClick() of your button, and override savedInstanceState and onRestoreInstanceState like so :
Code:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save state changes to the savedInstanceState.
// This bundle will be passed to onCreate if th activity is
// killed and restarted.
savedInstanceState.putBoolean("inflate", isInflated);
}
Code:
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
Boolean myBoolean = savedInstanceState.getBoolean("inflate");
if (myBoolean == true)
plusLayout(myView);
}
Using the sharedPreferences
Same logic, different way to save the boolean :
Before onCreate(), declare a private boolean and a private SharedPreferences :
Code:
private Boolean isInflated = false;
private SharedPreferences prefs = getSharedPreferences("MY_PREFS");
in the onClick of your button :
Code:
isInflated = true;
Editor e = prefs.edit();
e.putBoolean("inflate", isInflated);
e.commit();
Then, in your onCreate(), retrieve the stored value and if it's true, call your plusLayout() method :
Code:
Boolean doInflate = prefs.getBoolean("inflate", false // this is the default value);
if (doInflate == true)
plusLayout(myView);
nikwen said:
Ah ok.
The point is: If you open the app or turn your device, the onCreate method is called. There you set a completely new layout. You would need to save that the layout is inflated (you could use a SharedPreferences entry) and inflate it in the onCreate method. If you just want it to appear again after turning the device, use the onSaveInstanceState method and the onRestoreInstanceState method. That would be better practice.
Look at the activity lifecycle.
Click to expand...
Click to collapse
Okay I'm working on that at the moment.
Whenever a layout is created an (int) "counter" get incremented.
I will save this "counter" in the SharedPreferences.
When the app starts layouts get created "counter" times.
Is this good practice?
It seems so strange that there isn't an easier way to save layout/activity states.
Edit:
Androguide.fr said:
Just so I'm sure I get this right :
The user launches the app, the layouts are not inflated
He presses a button which calls your plusLayout() method, so the layouts are now inflated
The user quits the activity and restarts it, the layouts are not inflated anymore but you want them to.
Is that correct ?
Click to expand...
Click to collapse
That is correct. Big thanks for the examples.
DaanJordaan said:
Okay I'm working on that at the moment.
Whenever a layout is created an (int) "counter" get incremented.
I will save this "counter" in the SharedPreferences.
When the app starts layouts get created "counter" times.
Is this good practice?
It seems so strange that there isn't an easier way to save layout/activity states.
Edit:
That is correct. Big thanks for the examples.
Click to expand...
Click to collapse
I would use his snippets. They are good (as always). Decide which one to use by what I have given above:
Just for turning:
onSaveInstanceState and onRestoreSavedInstanceState
For turning and reopening:
Shared preferences

start building app.. and immediately need your help

Hello.
I'm very new to app developing but for starting learning I'd like to modify an app I have, doing two things:
1) in this app I have an edit text (with the cursor blinking) and a custom keyboard (not the system one, but one just of that app) for writing on it (something like a lockscreen). The problem is that whenever I press the keyboard buttons, despide of seeing my touch on them, nothing appear in the edit text.
Here's the layout.xml
Code:
<com.android.internal.widget.PasswordEntryKeyboardView android:id="@id/keyboard" android:background="#00000000" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:keyBackground="@drawable/btn_keyboard_key_fulltrans" />
Is this right?
Where can I find why it's not writing? In the PasswordEntryKeyboardView.smali?
2) I'd like also to have the status bar visible but not expandable. I've found I should do it putting a overlay over status bar and consumed all input events. So I'd need a custom class which extends any layout and consumes touch event and then to consume touch event override the onInterceptTouchEvent method of the view group and return true.
This should be the code for that custom class (customViewGroup):
Code:
WindowManager manager = ((WindowManager) getApplicationContext()
.getSystemService(Context.WINDOW_SERVICE));
WindowManager.LayoutParams localLayoutParams = new WindowManager.LayoutParams();
localLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
localLayoutParams.gravity = Gravity.TOP;
localLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
// this is to enable the notification to recieve touch events
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
// Draws over status bar
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
localLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
localLayoutParams.height = (int) (50 * getResources()
.getDisplayMetrics().scaledDensity);
localLayoutParams.format = PixelFormat.TRANSPARENT;
customViewGroup view = new customViewGroup(this);
manager.addView(view, localLayoutParams);
So, how to do it...
Do I have to add a new .smali in the widget folder with that code or can I add that code in a file there?
And how to override the onInterceptTouchEvent method of the view group and return true?
And how to remove it when I leave that app?
I hope someone helps me learning.
Thanks.

Categories

Resources