Android Launch Service Using Broadcast Receiver

I am implementing the following code in which I want to start a service using a broadcast receiver. The toast in the broadcast receiver is working fine, but the service is not running. Can someone tell me where I was wrong?

MyReceiver.class public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context arg0, Intent arg1) { // TODO Auto-generated method stub //Toast.makeText(arg0, "Service", Toast.LENGTH_LONG).show(); Intent myIntent = new Intent(arg0,MyS.class); arg0.startService(myIntent); } } MyS.class public class MyS extends Service { @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { // TODO Auto-generated method stub Toast.makeText(getBaseContext(), "Service started", Toast.LENGTH_LONG).show(); return START_STICKY; } } AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.test.p" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <service android:enabled="true" android:name=".MyS" > <intent-filter> <action android:name="com.test.p.MyS" > </action> </intent-filter> </service> <receiver android:enabled="true" android:name=".MyReceiver" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver> </application> </manifest> 
+6
source share
2 answers

Create a BroadcastReceiver variable in your activity

  private BroadcastReceiver mBootCompletedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // start your service right here... } }; 

and onCreate or onResume Activity events, you must register for this BroadcastReceiver

 super.registerReceiver(mBootCompletedReceiver, new IntentFilter("android.intent.action.BOOT_COMPLETED")); 

and onDestory or onStop or onPause, regardless of whether you have to unregister this BroadcastReceiver in a situation so as not to receive these updates anymore.

 super.unregisterReceiver(mBootCompletedReceiver); 
-1
source

A service is started only when there is an onreceive method called coz u that gave startervice inside the receive method. This means that you need to start some operations with the receiver, such as a call or SMS, to start the service. U may instead start the service at boot. Google it.

-3
source

Source: https://habr.com/ru/post/946996/


All Articles