Example: Communication between Activity and Service using Messaging

前端 未结 9 903
既然无缘
既然无缘 2020-11-22 00:06

I couldn\'t find any examples of how to send messages between an activity and a service, and I have spent far too many hours figuring this out. Here is an example project fo

9条回答
  •  佛祖请我去吃肉
    2020-11-22 00:42

    Great tutorial, fantastic presentation. Neat, simple, short and very explanatory. Although, notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent); method is no more. As trante stated here, good approach would be:

    private static final int NOTIFICATION_ID = 45349;
    
    private void showNotification() {
        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("My Notification Title")
                        .setContentText("Something interesting happened");
    
        Intent targetIntent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);
        _nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        _nManager.notify(NOTIFICATION_ID, builder.build());
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (_timer != null) {_timer.cancel();}
        _counter=0;
        _nManager.cancel(NOTIFICATION_ID); // Cancel the persistent notification.
        Log.i("PlaybackService", "Service Stopped.");
        _isRunning = false;
    }
    

    Checked myself, everything works like a charm (activity and service names may differ from original).

提交回复
热议问题