Android - एक सेवा के लिए startForeground को लागू करना?


124

इसलिए मुझे यह सुनिश्चित नहीं है कि अग्रभूमि में अपनी सेवा चलाने के लिए इस विधि को कहाँ / कैसे लागू किया जाए। वर्तमान में मैं एक अन्य गतिविधि में निम्नलिखित द्वारा अपनी सेवा शुरू करता हूं:

Intent i = new Intent(context, myService.class); 
context.startService(i);

और फिर myServices 'onCreate () में मैं स्टार्टफोरग्राउंड () की कोशिश करता हूं ...?

Notification notification = new Notification();
startForeground(1, notification);

तो हाँ, मैं थोड़ा खो गया हूं और इसे लागू करने के तरीके के बारे में अनिश्चित हूं।


खैर यह काम नहीं करता है, कम से कम जहाँ तक मैं अपनी सेवा बता सकता हूँ अभी भी एक पृष्ठभूमि सेवा के रूप में काम करता है और मार दिया जाता है।
जेडीएस

थ्रेड जुड़ा हुआ है: stackoverflow.com/questions/10962418/…
स्निकॉल

जवाबों:


131

मैं पूरी तरह से भरने से शुरू करूँगा Notificationयहाँ एक नमूना परियोजना है जिसके उपयोग का प्रदर्शन किया गया है startForeground()


8
क्या अधिसूचना के बिना startForeground () का उपयोग करना संभव है? या हम बाद में उसी अधिसूचना को अपडेट कर सकते हैं?
JRC

2
क्या कोई विशेष कारण है जिसका आपने उपयोग किया है 1337?
कोडी

33
@DoctorOreo: यह एप्लिकेशन के भीतर अद्वितीय होने की आवश्यकता है, हालांकि डिवाइस पर जरूरी नहीं है। मैंने 1337 को चुना क्योंकि, यह 1337 है । :-)
कॉमन्सवेयर

@JRC प्रश्न एक अच्छा है। क्या अधिसूचना के बिना startForeground () का उपयोग करना संभव है?
स्निकोलस

2
@ सिनोलस: एंड्रॉइड में एक दोष को इंगित करने के लिए धन्यवाद। मैं इसे ठीक करवाने पर काम करूंगा।
कॉमन्सवेयर

78

अपनी मुख्य गतिविधि से, निम्नलिखित कोड के साथ सेवा शुरू करें:

Intent i = new Intent(context, MyService.class); 
context.startService(i);

फिर आपकी सेवा में onCreate()आप अपनी अधिसूचना का निर्माण करेंगे और इसे अग्रभूमि की तरह सेट करेंगे:

Intent notificationIntent = new Intent(this, MainActivity.class);

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);

Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.app_icon)
                .setContentTitle("My Awesome App")
                .setContentText("Doing some work...")
                .setContentIntent(pendingIntent).build();

startForeground(1337, notification);

@ इस सूचना को MainActivity से कैसे अपडेट करें?
Roon13

1
@ Roon13 ID का उपयोग करते हुए, इस मामले में 1337 ... आपको एक नई अधिसूचना बनाने में सक्षम होना चाहिए और आईडी के साथ स्टार्ट-ऑनग्राउंड कॉल करना चाहिए
mikebertiean

@ Roon13 इस सवाल की जाँच करें stackoverflow.com/questions/5528288/…
mikebertiean

@mikebertiean मैं मेनऑक्टिविटी से स्टार्टफोरग्राउंड कैसे कह सकता हूं? यह भी कि जब प्रक्रिया समाप्त हो जाती है, तो मैं MainActvity से नोटिफिकेशन को कैसे साफ कर सकता हूं?
Roon13

@ मायिकबेटेरियन मुझे समझ में आया कि मुझे सर्विस क्लास में फिर से स्टार्टग्राउंड बुलाना है लेकिन कैसे? क्या मुझे फिर से startService () को कॉल करना है?
Roon13

30

सेवा को अग्रभूमि में सेट करने के लिए यह मेरा कोड है:

private void runAsForeground(){
    Intent notificationIntent = new Intent(this, RecorderMainActivity.class);
    PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
            notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

    Notification notification=new NotificationCompat.Builder(this)
                                .setSmallIcon(R.drawable.ic_launcher)
                                .setContentText(getString(R.string.isRecording))
                                .setContentIntent(pendingIntent).build();

    startForeground(NOTIFICATION_ID, notification);

}

मुझे PendingIntent का उपयोग करके एक अधिसूचना बनाने की आवश्यकता है, ताकि मैं अधिसूचना से अपनी मुख्य गतिविधि शुरू कर सकूं।

अधिसूचना को हटाने के लिए, बस स्टॉपफोरग्राउंड (सच) को कॉल करें;

इसे onStartCommand () में कहा जाता है। कृपया मेरे कोड को यहां देखें: https://github.com/bearstand/greyparrot/blob/master/src/com/xiong/richard/greyparrot/Mp3Recorder.java


यदि आप नोटिफिकेशन कॉलिंग को रोक देते हैं तोहफ़रग्राउंड (सच) आप स्टार्टरग्राउंड सर्विस रद्द कर रहे हैं
sdelvalle57

6
आप इस विधि को कहां से कहते हैं?
सर्जन बरई

7
Intent.FLAG_ACTIVITY_NEW_TASKके संदर्भ में मान्य नहीं है PendingIntent
मिश्रण

30

Oreo 8.1 के लिए समाधान

मुझे कुछ समस्याओं का सामना करना पड़ा है जैसे कि एंड्रॉइड के अधिकांश हाल के संस्करणों के साथ अमान्य चैनल आईडी के कारण RemoteServiceException । इस तरह मैंने इसे हल किया है:

गतिविधि :

override fun onCreate(savedInstanceState: Bundle?) {
    val intent = Intent(this, BackgroundService::class.java)

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForegroundService(intent)
    } else {
        startService(intent)
    }
}

BackgroundService:

override fun onCreate() {
    super.onCreate()
    startForeground()
}

private fun startForeground() {

    val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    val channelId =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                createNotificationChannel()
            } else {
                // If earlier version channel ID is not used
                // https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#NotificationCompat.Builder(android.content.Context)
                ""
            }

    val notificationBuilder = NotificationCompat.Builder(this, channelId )
    val notification = notificationBuilder.setOngoing(true)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setPriority(PRIORITY_MIN)
            .setCategory(Notification.CATEGORY_SERVICE)
            .build()
    startForeground(101, notification)
}


@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(): String{
    val channelId = "my_service"
    val channelName = "My Background Service"
    val chan = NotificationChannel(channelId,
            channelName, NotificationManager.IMPORTANCE_HIGH)
    chan.lightColor = Color.BLUE
    chan.importance = NotificationManager.IMPORTANCE_NONE
    chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
    val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    service.createNotificationChannel(chan)
    return channelId
}

जावा एक्विजेंट

public class YourService extends Service {

    // Constants
    private static final int ID_SERVICE = 101;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        // do stuff like register for BroadcastReceiver, etc.

        // Create the Foreground Service
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? createNotificationChannel(notificationManager) : "";
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
        Notification notification = notificationBuilder.setOngoing(true)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(PRIORITY_MIN)
                .setCategory(NotificationCompat.CATEGORY_SERVICE)
                .build();

        startForeground(ID_SERVICE, notification);
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private String createNotificationChannel(NotificationManager notificationManager){
        String channelId = "my_service_channelid";
        String channelName = "My Foreground Service";
        NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
        // omitted the LED color
        channel.setImportance(NotificationManager.IMPORTANCE_NONE);
        channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        notificationManager.createNotificationChannel(channel);
        return channelId;
    }
}

8
आप ContextCompat.startForegroundService(Context,Intent)अपनी गतिविधि में उपयोग कर सकते हैं जो सही काम करेगा। ( developer.android.com/reference/android/support/v4/content/… )
साइमन फेदरस्टोन

3
आप शायद का उपयोग करना चाहेंगे .setCategory(NotificationCompat.CATEGORY_SERVICE)के बजाय Notification.CATEGORY_SERVICEअगर आपके मिनट एपीआई <21 है
किसी ने कहीं न कहीं

6
कृपया ध्यान दें कि एप्लिकेशन लक्ष्यीकरण Build.VERSION_CODES.P(API स्तर 28) या बाद Manifest.permission.FOREGROUND_SERVICEमें उपयोग करने के लिए अनुमति का अनुरोध करना होगा startForeground()- डेवलपर
Vadim Kotov

21

RAWA जवाब के अलावा , कोड की यह शांति:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    startForegroundService(intent)
} else {
    startService(intent)
}

आप इसे बदल सकते हैं:

ContextCompat.startForegroundService(context, yourIntent);

यदि आप इस विधि के अंदर देखेंगे तो आप देख सकते हैं कि यह विधि आपके लिए सभी जाँच कार्य करती है।


9

यदि आप IntentService को एक अग्रभूमि सेवा बनाना चाहते हैं

फिर आपको onHandleIntent()इस तरह से ओवरराइड करना चाहिए

Override
protected void onHandleIntent(@Nullable Intent intent) {


    startForeground(FOREGROUND_ID,getNotification());     //<-- Makes Foreground

   // Do something

    stopForeground(true);                                // <-- Makes it again a normal Service                         

}

कैसे करें नोटिफिकेशन?

सरल। यहाँ getNotification()विधि है

public Notification getNotification()
{

    Intent intent = new Intent(this, SecondActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);


    NotificationCompat.Builder foregroundNotification = new NotificationCompat.Builder(this);
    foregroundNotification.setOngoing(true);

    foregroundNotification.setContentTitle("MY Foreground Notification")
            .setContentText("This is the first foreground notification Peace")
            .setSmallIcon(android.R.drawable.ic_btn_speak_now)
            .setContentIntent(pendingIntent);


    return foregroundNotification.build();
}

गहरी समझ

जब कोई सेवा अग्रभूमि सेवा बन जाती है तो क्या होता है

ऐसा होता है

यहाँ छवि विवरण दर्ज करें

अग्रभूमि सेवा क्या है?

एक अग्रभूमि सेवा,

  • सुनिश्चित करें कि उपयोगकर्ता सक्रिय रूप से इस बात से अवगत है कि अधिसूचना प्रदान करके पृष्ठभूमि में कुछ चल रहा है।

  • (सबसे महत्वपूर्ण बात) सिस्टम द्वारा नहीं मारा जाता है जब यह स्मृति पर कम चलता है

अग्रभूमि सेवा का उपयोग मामला

एक संगीत ऐप में गीत डाउनलोड की कार्यक्षमता को लागू करना


5

"ओएस> = Build.VERSION_CODES.O" के लिए दिया कोड सेवा वर्ग जोड़े onCreate में ()

@Override
public void onCreate(){
    super.onCreate();

     .................................
     .................................

    //For creating the Foreground Service
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    String channelId = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? getNotificationChannel(notificationManager) : "";
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId);
    Notification notification = notificationBuilder.setOngoing(true)
            .setSmallIcon(R.mipmap.ic_launcher)
           // .setPriority(PRIORITY_MIN)
            .setCategory(NotificationCompat.CATEGORY_SERVICE)
            .build();

    startForeground(110, notification);
}



@RequiresApi(Build.VERSION_CODES.O)
private String getNotificationChannel(NotificationManager notificationManager){
    String channelId = "channelid";
    String channelName = getResources().getString(R.string.app_name);
    NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
    channel.setImportance(NotificationManager.IMPORTANCE_NONE);
    channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
    notificationManager.createNotificationChannel(channel);
    return channelId;
}

इस अनुमति को प्रकट फ़ाइल में जोड़ें:

 <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

1

का उपयोग करके सेवा के startCommand पर इरादे संभाल ।

 stopForeground(true)

यह कॉल अग्रभूमि स्थिति से सेवा को हटा देगा , अगर अधिक मेमोरी की आवश्यकता हो तो इसे मार दिया जा सकता है। यह सेवा को चलाने से नहीं रोकता है । उसके लिए, आपको stopSelf () या संबंधित विधियों को कॉल करना होगा

यदि आप अधिसूचना को हटाना चाहते हैं या नहीं तो पासिंग वैल्यू सही या गलत है।

val ACTION_STOP_SERVICE = "stop_service"
val NOTIFICATION_ID_SERVICE = 1
...  
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
    super.onStartCommand(intent, flags, startId)
    if (ACTION_STOP_SERVICE == intent.action) {
        stopForeground(true)
        stopSelf()
    } else {
        //Start your task

        //Send forground notification that a service will run in background.
        sendServiceNotification(this)
    }
    return Service.START_NOT_STICKY
}

जब विनाश पर रोक () द्वारा कहा जाता है अपने काम को संभाल ।

override fun onDestroy() {
    super.onDestroy()
    //Stop whatever you started
}

सेवा को अग्रभूमि में रखने के लिए एक अधिसूचना बनाएं।

//This is from Util class so as not to cloud your service
fun sendServiceNotification(myService: Service) {
    val notificationTitle = "Service running"
    val notificationContent = "<My app> is using <service name> "
    val actionButtonText = "Stop"
    //Check android version and create channel for Android O and above
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        //You can do this on your own
        //createNotificationChannel(CHANNEL_ID_SERVICE)
    }
    //Build notification
    val notificationBuilder = NotificationCompat.Builder(applicationContext, CHANNEL_ID_SERVICE)
    notificationBuilder.setAutoCancel(true)
            .setDefaults(NotificationCompat.DEFAULT_ALL)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.ic_location)
            .setContentTitle(notificationTitle)
            .setContentText(notificationContent)
            .setVibrate(null)
    //Add stop button on notification
    val pStopSelf = createStopButtonIntent(myService)
    notificationBuilder.addAction(R.drawable.ic_location, actionButtonText, pStopSelf)
    //Build notification
    val notificationManagerCompact = NotificationManagerCompat.from(applicationContext)
    notificationManagerCompact.notify(NOTIFICATION_ID_SERVICE, notificationBuilder.build())
    val notification = notificationBuilder.build()
    //Start notification in foreground to let user know which service is running.
    myService.startForeground(NOTIFICATION_ID_SERVICE, notification)
    //Send notification
    notificationManagerCompact.notify(NOTIFICATION_ID_SERVICE, notification)
}

उपयोगकर्ता की आवश्यकता होने पर सेवा को रोकने के लिए अधिसूचना पर एक स्टॉप बटन दें।

/**
 * Function to create stop button intent to stop the service.
 */
private fun createStopButtonIntent(myService: Service): PendingIntent? {
    val stopSelf = Intent(applicationContext, MyService::class.java)
    stopSelf.action = ACTION_STOP_SERVICE
    return PendingIntent.getService(myService, 0,
            stopSelf, PendingIntent.FLAG_CANCEL_CURRENT)
}

1

नोट: यदि आपका ऐप एपीआई स्तर 26 या उच्चतर को लक्षित करता है, तो सिस्टम पृष्ठभूमि सेवाओं का उपयोग करने या बनाने पर प्रतिबंध लगाता है जब तक कि ऐप स्वयं अग्रभूमि में न हो।

यदि किसी ऐप को अग्रभूमि सेवा बनाने की आवश्यकता है, तो ऐप को कॉल करना चाहिए startForegroundService()वह विधि एक पृष्ठभूमि सेवा बनाती है, लेकिन विधि प्रणाली को संकेत देती है कि सेवा अग्रभूमि में खुद को बढ़ावा देगी।

एक बार सेवा बन जाने के बाद, सेवा को कॉल करना होगा startForeground() method within five seconds.


1
मुझे आशा है कि आप वर्तमान प्रश्न के बारे में बात कर रहे हैं। अन्यथा, स्टाकेओवरफ़्लो समुदाय में ऐसा कोई नियम नहीं है
फ़रीद

उत्पादन-तैयार पर्यावरण कोड में @RogerGusmao हमेशा आपकी परियोजना को नहीं बचाएगा। इसके अलावा - मेरे जवाब के नीचे और ऊपर कोड के साथ बहुत सारे उदाहरण हैं .. मेरी परियोजना को रिलीज के दौरान बिल्कुल मुद्दे थे क्योंकि मुझे startForegroundServiceविधि के बारे में पता नहीं था
एंड्री कोवलचुक

0

मेरे मामले में यह पूरी तरह से अलग था क्योंकि मुझे ओरेओ में सेवा लॉन्च करने के लिए गतिविधि नहीं हो रही थी।

नीचे वे चरण दिए गए हैं जिनका उपयोग मैंने इस अग्रभूमि सेवा समस्या को हल करने के लिए किया है -

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;
    }
}

और उसके बाद इस सेवा को शुरू करने के लिए मैं cmd ​​से नीचे चला आया -


adb -s "+ serial_id +" शेल am startforegroundservice -n com.test.socket .sample / .SocketService है।


तो यह मुझे Oreo उपकरणों पर गतिविधि के बिना सेवा शुरू करने में मदद करता है :)


0

@mikebertiean समाधान ने लगभग चाल चली, लेकिन मुझे अतिरिक्त मोड़ के साथ यह समस्या थी - मैं जिंजरब्रेड प्रणाली का उपयोग करता हूं और मैं केवल अधिसूचना चलाने के लिए कुछ अतिरिक्त पैकेज जोड़ना नहीं चाहता था। अंत में मैंने पाया: https://android.googlesource.com/platform/frameworks/support.it+/f9fd97499795cd47473f0344e00db9c9837eea36/v4/gingerbread/android/support/v4/app/NotificationCompatGingerbread.java

फिर मैंने अतिरिक्त समस्या को मारा - अधिसूचना केवल तभी मेरे ऐप को मारती है जब यह चलता है (इस समस्या को हल करने के लिए कैसे: एंड्रॉइड: कैसे बचें कि नोटिफिकेशन कॉल onCreate () ) पर क्लिक करें , इसलिए कुल मिलाकर सेवा में मेरा कोड इस तरह दिखता है (C # / Xamarin):

Intent notificationIntent = new Intent(this, typeof(MainActivity));
// make the changes to manifest as well
notificationIntent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop);
PendingIntent pendingIntent = PendingIntent.GetActivity(this, 0, notificationIntent, 0);
Notification notification = new Notification(Resource.Drawable.Icon, "Starting service");
notification.SetLatestEventInfo(this, "MyApp", "Monitoring...", pendingIntent);
StartForeground(1337, notification);
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.