Android - implementing startForeground for a service?

前端 未结 11 1320
不思量自难忘°
不思量自难忘° 2020-11-22 06:26

So I\'m not sure where/how to implement this method to make my service run in the foreground. Currently I start my service by the following in another activity:

<         


        
11条回答
  •  借酒劲吻你
    2020-11-22 07:16

    In my case It was totally different since I was not having activity to launch the service in Oreo.

    Below are the steps which I used to resolve this foreground service issue -

    public class SocketService extends Service {
        private String TAG = this.getClass().getSimpleName();
    
        @Override
        public void onCreate() {
            Log.d(TAG, "Inside onCreate() API");
            if (Build.VERSION.SDK_INT >= 26) {
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
                mBuilder.setSmallIcon(R.drawable.ic_launcher);
                mBuilder.setContentTitle("Notification Alert, Click Me!");
                mBuilder.setContentText("Hi, This is Android Notification Detail!");
                NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
                // notificationID allows you to update the notification later on.
                mNotificationManager.notify(100, mBuilder.build());
                startForeground(100, mBuilder.mNotification);
            }
            Toast.makeText(getApplicationContext(), "inside onCreate()", Toast.LENGTH_LONG).show();
        }
    
    
        @Override
        public int onStartCommand(Intent resultIntent, int resultCode, int startId) {
            Log.d(TAG, "inside onStartCommand() API");
    
            return startId;
        }
    
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            Log.d(TAG, "inside onDestroy() API");
    
        }
    
        @Override
        public IBinder onBind(Intent intent) {
            // TODO Auto-generated method stub
            return null;
        }
    }
    

    And after that to initiate this service I triggered below cmd -


    adb -s " + serial_id + " shell am startforegroundservice -n com.test.socket.sample/.SocketService


    So this helps me to start service without activity on Oreo devices :)

提交回复
热议问题