从通知开始服务

时间:2011-06-21 08:21:07

标签: android service notifications

是否可以从通知中启动服务。 启动活动的正常方式是完美的,但在实际启动应用程序之前我需要对数据进行一些预先检查。

我已经通过在通知意图中包含有效服务来测试它,但没有任何反应。

4 个答案:

答案 0 :(得分:70)

  

可以通过通知启动服务。

您必须使用PendingIntent.getService而不是pendingIntent.getActivity。

Intent notificationIntent = new Intent(mContext, HandleNotificationClickService.class);
PendingIntent pendingIntent = PendingIntent.getService(mContext, 0, notificationIntent, 0);

Notification notification = new Notification(icon, tickerText,System.currentTimeMillis());
notification.setLatestEventInfo(mContext,contentTitle , contentText, pendingIntent);
notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONGOING_EVENT;

NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

notificationManager.notify(CALLER_ID_NOTIFICATION_ID, notification);

答案 1 :(得分:5)

创建广播接收器,从通知接收消息,然后启动服务。

答案 2 :(得分:1)

element.parent().find()

答案 3 :(得分:0)

对我来说,这非常有效。 我将写下整个示例。 您可以根据需要修改答案

这是用于创建通知的

public void createNotification2(String aMessage) {
    final int NOTIFY_ID = 11;
    String name = getString(R.string.app_name);
    String id = getString(R.string.app_name); // The user-visible name of the channel.
    String description = 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) {
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel mChannel = notifManager.getNotificationChannel(id);
        if (mChannel == null) {
            mChannel = new NotificationChannel(id, name, importance);
            mChannel.setDescription(description);
            mChannel.enableVibration(true);
            mChannel.setLightColor(getColor(R.color.colorPrimaryDark));
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            notifManager.createNotificationChannel(mChannel);
        }
    } else {

    }
    Intent Off_broadcastIntent = new Intent(this, Database_Update.class);
    Off_broadcastIntent.setAction("on");
    Off_broadcastIntent.putExtra("toastMessage", "1");
    PendingIntent Off_actionIntent = PendingIntent.getService(this, 0, Off_broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent on_broadcastIntent = new Intent(this, Database_Update.class);
    on_broadcastIntent.setAction("off");
    on_broadcastIntent.putExtra("toastMessage", "0");
    PendingIntent on_actionIntent = PendingIntent.getService(this, 0, on_broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent cancel_broadcastIntent = new Intent(this, Database_Update.class);
    cancel_broadcastIntent.setAction("cancel");
    cancel_broadcastIntent.putExtra("toastMessage", "close");
    PendingIntent cancel_actionIntent = PendingIntent.getService(this, 0, cancel_broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent content_intent = new Intent(this, Status_Page.class);
    content_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, content_intent, PendingIntent.FLAG_UPDATE_CURRENT);


    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, id)
            .setSmallIcon(android.R.drawable.ic_popup_reminder)
            .setContentTitle(name)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setContentIntent(pendingIntent)
            .setAutoCancel(false)
            .setVibrate(new long[]{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);
    Notification notification = mBuilder.build();
    notification.flags = Notification.FLAG_NO_CLEAR|Notification.FLAG_ONGOING_EVENT;
    notifManager.notify(11, notification);
}

在Android Menifest中

<service android:name=".Database_Update"></service>

这是服务等级

public class Database_Update extends Service {
String result="";

Realm realm;
BlockList blockList;
@Override
public void onCreate() {
    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
public int onStartCommand(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();
    }else if (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();
    }else if (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 null
    return null;
}

@Override
public void onDestroy() {
    if (realm!=null){
        realm.close();
    }
    Toast.makeText(this, "REMOVING", Toast.LENGTH_SHORT).show();
}
}