Foreground service example

后端 未结 2 1562
无人及你
无人及你 2020-12-28 20:46

I am new to android. Can anyone post the link or code for \"android foreground service example with notification\". I googled , but didn\'t get any example of foreground ser

2条回答
  •  渐次进展
    2020-12-28 20:57

    A better example would be:

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
    Log.i(LOG_TAG, "Received Start Foreground Intent ");
    Intent notificationIntent = new Intent(this, MainActivity.class);
    notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
    | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
    notificationIntent, 0);
    
    Intent previousIntent = new Intent(this, ForegroundService.class);
    previousIntent.setAction(Constants.ACTION.PREV_ACTION);
    PendingIntent ppreviousIntent = PendingIntent.getService(this, 0,
    previousIntent, 0);
    
    Intent playIntent = new Intent(this, ForegroundService.class);
    playIntent.setAction(Constants.ACTION.PLAY_ACTION);
    PendingIntent pplayIntent = PendingIntent.getService(this, 0,
    playIntent, 0);
    
    Intent nextIntent = new Intent(this, ForegroundService.class);
    nextIntent.setAction(Constants.ACTION.NEXT_ACTION);
    PendingIntent pnextIntent = PendingIntent.getService(this, 0,
    nextIntent, 0);
    
    Bitmap icon = BitmapFactory.decodeResource(getResources(),
    R.drawable.truiton_short);
    
    Notification notification = new NotificationCompat.Builder(this)
    .setContentTitle("Truiton Music Player")
    .setTicker("Truiton Music Player")
    .setContentText("My Music")
    .setSmallIcon(R.drawable.ic_launcher)
    .setLargeIcon(
    Bitmap.createScaledBitmap(icon, 128, 128, false))
    .setContentIntent(pendingIntent)
    .setOngoing(true)
    .addAction(android.R.drawable.ic_media_previous,
    "Previous", ppreviousIntent)
    .addAction(android.R.drawable.ic_media_play, "Play",
    pplayIntent)
    .addAction(android.R.drawable.ic_media_next, "Next",
    pnextIntent).build();
    startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE,
    notification);
    } else if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) {
    Log.i(LOG_TAG, "Clicked Previous");
    } else if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) {
    Log.i(LOG_TAG, "Clicked Play");
    } else if (intent.getAction().equals(Constants.ACTION.NEXT_ACTION)) {
    Log.i(LOG_TAG, "Clicked Next");
    } else if (intent.getAction().equals(
    Constants.ACTION.STOPFOREGROUND_ACTION)) {
    Log.i(LOG_TAG, "Received Stop Foreground Intent");
    stopForeground(true);
    stopSelf();
    }
    return START_STICKY;
    }
    

    Took reference from a tutorial here.. maybe of help to you

提交回复
热议问题