Changing Notifications on android code to use notification.builder - java

I am not a developer, and am trying to get some sample code working nicely.
The API I am running against, is not 100% compatible with my code I am using.(API15).
Would anyone be able to help me reformat this code to work with the newer style builder notifications?
(I had a try, but cant work out the right way of doing it based on the question linked)
{
Notification notification = new Notification(R.drawable.ic_launcher, "Robot service running", System.currentTimeMillis());
notification.setLatestEventInfo(this, "Robot Service", "Click to stop", PendingIntent.getService(this, 0, new Intent("stop", null, this, this.getClass()), 0));
notification.flags |= Notification.FLAG_ONGOING_EVENT;
nm.notify(0, notification);
}

Notification noti = new Notification.Builder(mContext)
.setContentTitle("New mail from " + sender.toString())
.setContentText(subject)
.setSmallIcon(R.drawable.new_mail)
.setLargeIcon(aBitmap)
.build();
For more detail use below link:
http://developer.android.com/reference/android/app/Notification.Builder.html

Related

“Protected Apps” setting on Android phones

We can ask the user to protect our app, by using (e.g. Huawei phones):
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity"));
startActivity(intent);
Is there a way of knowing if the app got protected or not? I'm trying to avoid asking the user to protect the app e.g. every time the app is created.
For other intents, I can use:
List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(
new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, Uri.parse("package:" + getPackageName()))
,
PackageManager.MATCH_DEFAULT_ONLY);
System.out.println("MY_intent_TEST_1(looks always true): "+( list.size() > 0 ) );
PowerManager pwm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
System.out.println("MY_intent_TEST_2(true when whitelisted): "+ pwm.isIgnoringBatteryOptimizations(context.getPackageName()) );
P.S. I'm learning from: "Protected Apps" setting on Huawei phones, and how to handle it
Because related interfaces are not exposed, currently you cannot get to know whether the app got protected or not.

How to delete or cancel all pendingIntent in alarmManager?

In my app, I would like to delete all pendingIntent in my alarmManager.
Is possible to do a for() to delete all?
Try this.
Android: Get all PendingIntents set with AlarmManager
To cancel all alarm, first you have to find all the pending intent for that and cancel alarm using that.
If it is helpful to you than don't miss to accept this as your answer.
// set up alarm
List<PendingIntent> mPendingIntentList = new ArrayList<PendingIntent>();
Intent alarmIntent = new Intent(getApplicationContext(),Receiver.class);
alarmIntent.setData(Uri.parse("custom://" + alarm.ID));
alarmIntent.setAction(String.valueOf(alarm.ID));
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent displayIntent = PendingIntent.getBroadcast(getContext(), 0, alarmIntent, 0);
// add pending intent in list
mPendingIntentList.add(displayIntent );
alarmManager.set(AlarmManager.RTC_WAKEUP, alarmDateTime, displayIntent);
//cancel all alarms
for(int idx = 0 ; idx < mPendingIntentList.size() ; idx++){
alarmManager .cancel(mPendingIntentList.get(idx));
}
See AlarmManager.cancel(PendingIntent)
Create a PendingIntent matching the intent(s) you wish to cancel. Calling the above function once, will cancel all matching alarms
.

Notification sound goes infinity and never stop

I made a notification with sound and when it notify make sound but never stop. Is there any way to limit the notification's sound time?
this is my notification code
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.drawable.icon)
.setContentTitle(title).setContentText(detail);
mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
mBuilder.setDefaults(Notification.DEFAULT_LIGHTS);
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(context);
String sound = pref.getString("ringtonePref", "default");
Uri uri = Uri.parse(sound);
mBuilder.setSound(uri,RingtoneManager.TYPE_ALARM);
Had the same problem. I used NotificationBuilder to build everything. Called build() to get the noti object and I did the following:
notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notification.audioStreamType = AudioManager.STREAM_NOTIFICATION;
I believe you need to change TYPE_ALARM to TYPE_NOTIFICATION.
Some of the ringtones contain ANDROID_LOOP metadata to make the music loop.
These sounds will loop forever. So it is better to use sounds specific for default notifications or sounds that doesn't have ANDROID_LOOP metadata.

How to execute one task every hour?

I have been developing an Android application and I need to execute 1 task every hour. I uses the following code for it:
private static final long ALARM_PERIOD = 1000L;
public static void initAlarmManager(Context context) {
Editor editor=PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putBoolean(context.getString(R.string.terminate_key), true).commit();
AlarmManager manager = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
Intent i = new Intent(context, AlarmEventReceiver.class);
PendingIntent receiver = PendingIntent.getBroadcast(context, 0, i, 0);
manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), ALARM_PERIOD, receiver);
}
It works for me, but my client tells me that the task works only 1 time and won't work 1 hour. Where have I made a mistake? Please, tell me. Thank you.
According to your code, ALARM_PERIOD is 1000L, as repeating interval. So I doubt the alarm will set of in every 1000 milliseconds.
if you are setting repeating interval for every hour, it should be 3600000L.
And take note that if the phone is restarted, your alarm manager will no longer work unless you start again.
Here is the my Code:
private void setAlarmManager() {
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 2, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
long l = new Date().getTime();
if (l < new Date().getTime()) {
l += 86400000; // start at next 24 hour
}
am.setRepeating(AlarmManager.RTC_WAKEUP, l, 86400000, sender); // 86400000
}
Have you added receiver tag in application tag in manifest.xml
<receiver android:name=".AlarmReceiver" android:process=":remote"/>
Instead of Alram-Manager I recommended you to use Android-TimerTask
The TimerTask class represents a task to run at a specified time. The task may be run once or repeatedly. Its perfect suits for your requirements.
Try by modifying your code by changing your setRepeating() method like this
manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime(), SystemClock.elapsedRealtime()+(60*60*1000), receiver);
OR
Test this it is repeating for every minute
manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,Calendar.getInstance().getTimeInMillis(), Calendar.getInstance().getTimeInMillis()+(1*60*1000), receiver);

Proximity Alert Intent not putting or returning extras

What I'm doing is adding different proximity alerts with a unique ID as an extra and it's not working -
for (int i = 0; i < latArray.size(); i++)
{
Bundle extra = new Bundle();
extra.putInt("UID", i);
Intent intent = new Intent(IntentToFire);
intent.putExtra("Blob", extra);
PendingIntent proximityIntent = PendingIntent.getBroadcast(this,-1 , intent, 0);
LocationManager locationManager =
Log.i("Picture:","Location img:"+GetLocation.imgArray.get(i));
Log.i("Potatoo:", "Lat :"+latArray.get(i)+" Lng :"+lngArray.get(i));
locationManager.addProximityAlert(Double.valueOf(latArray.get(i)), Double.valueOf(lngArray.get(i)), radius,expiration,proximityIntent);
}
And then on the broadcast receiver I'm putting this code -
flag = intent.getBundleExtra("blob").getInt("UID");
Every time I got to print flag, I just get an error. An ideas?
Try to use the FLAG_UPDATE_CURRENT:
PendingIntent.getBroadcast(this,-1 , intent, PendingIntent.FLAG_UPDATE_CURRENT);
I found it easiest is to encode data in the data-uri with proximity alerts on the Intent that is included in the pending intent, e.x.:
geo:<lat>,<lon>?id=<your id>
You can use your own protocol part though (geo is used by google maps AFAIK). No caching problems for me (seems you get a cached/old/wrong PendingIntent).

Categories

Resources