Start Service From Notification
is it possible to start a service from a notification. The normal way of starting an activity is working perfectly, but I need some pre checks of data before actually starting the
Solution 1:
It is possible to start a service from a notification.
You have to use PendingIntent.getService instead of pendingIntent.getActivity.
IntentnotificationIntent=newIntent(mContext, HandleNotificationClickService.class);
PendingIntentpendingIntent= PendingIntent.getService(mContext, 0, notificationIntent, 0);
Notificationnotification=newNotification(icon, tickerText,System.currentTimeMillis());
notification.setLatestEventInfo(mContext,contentTitle , contentText, pendingIntent);
notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONGOING_EVENT;
NotificationManagernotificationManager= (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(CALLER_ID_NOTIFICATION_ID, notification);
Solution 2:
Solution 3:
privatevoidcreateNotification(String message)
{
Intentintent=newIntent(this, Yourservice.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntentpendingIntent= PendingIntent.getService(this, 0/* Request code */, intent,
0);
NotificationCompat.BuildernotificationBuilder= (NotificationCompat.Builder) newNotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icond)
.setContentTitle("Start Launcher")
.setContentText(message)
.setAutoCancel(true)
.setOngoing(true)
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent);
NotificationManagernotificationManager= (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(ID_NOTIFICATION , notificationBuilder.build());
}
Solution 4:
For me, this is working greatly.. I will write down the whole example.. you can modify the answer if you need it
This is for Notification create
publicvoidcreateNotification2(String aMessage) {
finalintNOTIFY_ID=11;
Stringname= getString(R.string.app_name);
Stringid= getString(R.string.app_name); // The user-visible name of the channel.Stringdescription= getString(R.string.app_name); // The user-visible description of the channel.
NotificationCompat.Builder builder;
if (notifManager == null) {
notifManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
intimportance= NotificationManager.IMPORTANCE_HIGH;
NotificationChannelmChannel= notifManager.getNotificationChannel(id);
if (mChannel == null) {
mChannel = newNotificationChannel(id, name, importance);
mChannel.setDescription(description);
mChannel.enableVibration(true);
mChannel.setLightColor(getColor(R.color.colorPrimaryDark));
mChannel.setVibrationPattern(newlong[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notifManager.createNotificationChannel(mChannel);
}
} else {
}
IntentOff_broadcastIntent=newIntent(this, Database_Update.class);
Off_broadcastIntent.setAction("on");
Off_broadcastIntent.putExtra("toastMessage", "1");
PendingIntentOff_actionIntent= PendingIntent.getService(this, 0, Off_broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intenton_broadcastIntent=newIntent(this, Database_Update.class);
on_broadcastIntent.setAction("off");
on_broadcastIntent.putExtra("toastMessage", "0");
PendingIntenton_actionIntent= PendingIntent.getService(this, 0, on_broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intentcancel_broadcastIntent=newIntent(this, Database_Update.class);
cancel_broadcastIntent.setAction("cancel");
cancel_broadcastIntent.putExtra("toastMessage", "close");
PendingIntentcancel_actionIntent= PendingIntent.getService(this, 0, cancel_broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intentcontent_intent=newIntent(this, Status_Page.class);
content_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntentpendingIntent= PendingIntent.getActivity(this, 0, content_intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.BuildermBuilder=newNotificationCompat.Builder(this, id)
.setSmallIcon(android.R.drawable.ic_popup_reminder)
.setContentTitle(name)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setAutoCancel(false)
.setVibrate(newlong[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.addAction(R.drawable.block, "ON", Off_actionIntent)
.addAction(R.drawable.notification, "OFF", on_actionIntent)
.addAction(R.drawable.clear, "CLOSE", cancel_actionIntent);
Notificationnotification= mBuilder.build();
notification.flags = Notification.FLAG_NO_CLEAR|Notification.FLAG_ONGOING_EVENT;
notifManager.notify(11, notification);
}
In Android Menifest
<serviceandroid:name=".Database_Update"></service>
This is service class
publicclassDatabase_UpdateextendsService {
String result="";
Realm realm;
BlockList blockList;
@Override
publicvoidonCreate() {
try {
RealmConfiguration config = new RealmConfiguration.Builder()
.name("notification.realm")
.schemaVersion(1)
.deleteRealmIfMigrationNeeded()
.build();
realm = Realm.getInstance(config);
} catch (Exception e) {
Log.d("Error Line Number", Log.getStackTraceString(e));
}
}
@Override
publicintonStartCommand(Intent intent, int flags, int startId) {
//Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
Log.d("SERVICE","SERVICE CHECKING");
result=intent.getStringExtra("toastMessage");
Log.d("SERVICE",result);
if (realm!=null){
Log.d("SERVICE","realm working");
}else {
Log.d("SERVICE","Realm not working");
}
blockList=realm.where(BlockList.class).equalTo("package_name", "BLOCK_ALL").findFirst();
try {
Log.d("SERVICE",blockList.getStatus());
} catch (Exception e) {
Log.d("Error Line Number", Log.getStackTraceString(e));
}
realm.beginTransaction();
if (result.equals("1")){
if (blockList==null){
BlockList blockList_new=realm.createObject(BlockList.class);
blockList_new.setPackage_name("BLOCK_ALL");
blockList_new.setStatus("yes");
}else {
blockList.setStatus("yes");
}
Log.d("SERVICE","BLOCKING NOTIFICATION");
Toast.makeText(this, "BLOCKING", Toast.LENGTH_SHORT).show();
}elseif (result.equals("0")){
if (blockList==null){
BlockList blockList_new=realm.createObject(BlockList.class);
blockList_new.setPackage_name("BLOCK_ALL");
blockList_new.setStatus("no");
}else {
blockList.setStatus("no");
}
Log.d("SERVICE","ALLOW NOTIFICATION");
Toast.makeText(this, "ALLOW NOTIFICATION", Toast.LENGTH_SHORT).show();
}elseif (result.equals("close")){
NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(11);
Log.d("SERVICE","REMOVING");
Toast.makeText(this, "CLOSED", Toast.LENGTH_SHORT).show();
}
realm.commitTransaction();
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return nullreturnnull;
}
@Override
publicvoidonDestroy() {
if (realm!=null){
realm.close();
}
Toast.makeText(this, "REMOVING", Toast.LENGTH_SHORT).show();
}
}
Post a Comment for "Start Service From Notification"