Android PendingIntent для службы foreGround - PullRequest
0 голосов
/ 10 августа 2011

Я все еще в замешательстве, когда запускаю службу на переднем плане.

В настоящее время: у меня есть действие, которое запускает службу в фоновом режиме, чтобы выполнить статистику по данным датчика + данные GPS. Его продолжают убивать, поэтому я начал его на переднем плане. Работает отлично. Однако, когда я касаюсь значка уведомления в строке состояния, кажется, что начинается новое действие (которое я указывал в Ожидающем намерении).

Итак, в двух словах, я все еще запутался со всем этим. Я хотел бы, чтобы действие запускало службу на переднем плане, и когда вы нажимаете на панель уведомлений, она переносит существующую активность, которая запустила службу, на передний план.

Вот код внутри действия (в настоящее время PendingIntent имеет значение null):

private ServiceConnection mConnection = new ServiceConnection() {
     public void onServiceConnected(ComponentName className, IBinder service) {
        // This is called when the connection with the service has been
        // established, giving us the service object we can use to
        // interact with the service. Because we have bound to a explicit
        // service that we know is running in our own process, we can
        // cast its IBinder to a concrete class and directly access it.

        cycleDataService = ((CycleDataProService.LocalBinder) service)
                .getService();
        //Todo the notification bullshaite here...
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
        int icon = R.drawable.icon;
        CharSequence tickerText = "Hello";
        long when = System.currentTimeMillis();
        Notification notification = new Notification(icon, tickerText, when);
        Context context = getApplicationContext();
        CharSequence contentTitle = "My notification";
        CharSequence contentText = "Hello World!";          
        //Intent notificationIntent = new Intent(cycleDataService, CycleDataProService.class);
        //PendingIntent contentIntent = PendingIntent.getActivity(context, 0, myOwnIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent pi = PendingIntent.getActivity(context, 0, null, 0);

        //PendingIntent contentIntent = PendingIntent.getActivity(context, 0, , 0);
        notification.setLatestEventInfo(context, contentTitle, contentText, pi);
        mNotificationManager.notify(HELLO_ID, notification);
        cycleDataService.startForeground(HELLO_ID, notification);
        /*cycleDataService.startService(new Intent(cycleDataService,
                CycleDataProService.class));*/
        serviceIsRunning = true;
        // Tell the user about this for our demo.
        // Toast.makeText(Binding.this, R.string.local_service_connected,
        // Toast.LENGTH_SHORT).show();
    }

Ответы [ 2 ]

2 голосов
/ 10 августа 2011

используйте таким образом:

Intent notificationIntent = new Intent(context, YourActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    notification.contentIntent = contentIntent;
    notification.setLatestEventInfo(context, "title", null, contentIntent);
0 голосов
/ 23 декабря 2014

Используйте FLAG_ACTIVITY_SINGLE_TOP, если хотите, чтобы ваша деятельность продолжалась, а не перезапускалась.

Intent notificationIntent = new Intent(context, YourActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.contentIntent = contentIntent;
notification.setLatestEventInfo(context, "title", null, contentIntent);
...