简体   繁体   中英

how to call activity from service?

I have created two projects. One project will act as a library and another as a main project. I will call the main project to library project, then the library project will send a notification. It's working fine but my question is if i click the notification it will go to main project activity. What can i do? Is it possible in android?

In library project :

    PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
            new Intent("com.sample.myapp.Monitor"), 0);
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            context).setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("Start Scheduler")
            .setContentText("Please start your activity!")
            .setContentIntent(contentIntent).setAutoCancel(true)
            .setLights(Color.RED, 1, 1);
    NotificationManager mNotificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(1, mBuilder.build());

here the com.sample.myapp.Monitor is main project activity.If i click the notification it does not call main project activity.

Finally i got the solution to connect my library project to main project activity.

Intent intent = new Intent(); intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity")); PendingIntent contentIntent = PendingIntent.getActivity(context, 0,intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);

I'm not sure if I understood you correctly, so you want to create a notification and when user clicks it you want to show him your Activity, right? In this case you can read Google documentation about that

EDIT: Here you can look a good example of creating a Service with BroadcastReceiver. I assume that your library does some background processing (perhaps in Service as well). So I would suggest the following scenario:

  1. Your application starts a service with registered BroadcastReceiver
  2. Your library project does some background processing and after that sends a broadcast as described in the example provided.
  3. Previosely registered BroadcastReceiver receives a broadcast and sends a notification with action pointing to your Activity (as described in the developer page from my original answer)
  4. User click notification and Activity opens.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM