How to get an application broadcast receiver to continue listening without having a service running in the background

I am trying to make an Android app that listens to Wi-Fi, changes the broadcast and does some actions. But the problem is that it does not work when the process is killed. I found this question which says that it will not work without activity. How to create BroadcastReceiver without activity / service?

So this is not an alternative. So I created an action that is empty. I do not want to create a service that runs in the background. How can I get the application to continue listening, even when it is killed. I registered the broadcast in the manifest.

<activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name="com.background.service.BroadCastReceiver"> <intent-filter> <action android:name="android.net.wifi.WIFI_STATE_CHANGED"/> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> 

This is my class

 public class BroadCastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //do some action } } 
+7
android android-intent android-broadcast
source share
6 answers

It looks like you have the correct definition in the manifest with one exception. The broadcast receiver initiates an ANR if it does not complete after 10 seconds. http://developer.android.com/training/articles/perf-anr.html

in your broadcast receiver just start the service.

 public class ReceiverUpload extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { context.startService(new Intent(context, ServiceUploader.class)); } } 

Then in your service, start asynctask because you do not want to be in the user interface thread, for example, you start the same service from activity in your application.

 @Override public int onStartCommand(Intent intent, int flags, int startId) { // start asynctask to get off this thread new MyBackGround().execute(startId); return Service.START_REDELIVER_INTENT; } 

The first thing you need to do in asintet is to check on wifi

The following is an excerpt from the function that I call to check the network if it returns false, asynchromatization just ends if it is true, it makes network materials that should be in the background anyway, so inactivation makes even more sense.

 // check for network connection ConnectivityManager connMgr = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connMgr == null) { return false; } // check ok to process NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo == null || !networkInfo.isConnected()) { return false; } boolean isWifi = networkInfo.getType() == ConnectivityManager.TYPE_WIFI; if (!isWifi) { return false; } return true; 

Note. In this example, startId passed to asynctask is used to cancel the OS reassigning the intent.

  @Override public void onPostExecute(Integer startId) { if (startId != null) { stopSelfResult(startId); } } 
+3
source share

The best thing that worked for me:

AndroidManifest

 <receiver android:name="com.AEDesign.communication.WifiReceiver" > <intent-filter android:priority="100"> <action android:name="android.net.wifi.STATE_CHANGE" /> </intent-filter> </receiver> 

Class BroadcastReceiver

 public class WifiReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); if(info != null) { if(info.isConnected()) { // Do your work. // eg To check the Network Name or other info: WifiManager wifiManager=(WifiManager)context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); String ssid = wifiInfo.getSSID(); } } } } 

Permissions

 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 
+2
source share

Usually, if the application is killed and broadcasts, the process of your application will be launched by the system for you. There is no need to save something alive or to do any additional manipulations (otherwise, why do you need BroadcastReceiver if you can just use the Service ?)

+1
source share

The best solution is to make a broadcast receiver, it will work

 public class NetworkChangeReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) { final ConnectivityManager connMgr = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); final android.net.NetworkInfo wifi = connMgr .getNetworkInfo(ConnectivityManager.TYPE_WIFI); final android.net.NetworkInfo mobile = connMgr .getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (wifi.isAvailable() || mobile.isAvailable()) { // Enjoy coding here Log.d("Netowk Available ", "Flag No 1"); } }} 

in manifest.xml

  <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.broadcastreceiverforinternetconnection" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <receiver android:name=".NetworkChangeReceiver" > <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> <action android:name="android.net.wifi.WIFI_STATE_CHANGED" /> </intent-filter> </receiver> </application> 

+1
source share

You are already right with the broadcast receiver and declare it a manifest. That is all you need. No services running in the background are needed.

Just make sure that you install and run the application at least once, otherwise the broadcast will not be registered.

+1
source share
  ` <receiver android:name=".GcmBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" > <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <category android:name="com.Reading.home" /> </intent-filter> </receiver> <service android:name=".GcmMessageHandler" /> 

`

 ` public class API_gettoken extends AsyncTask { Context context; API_gettoken(Context context) { this.context = context; } InterfaceSimpleStringResponce responce; String regid; void getresponce(InterfaceSimpleStringResponce responce) { this.responce = responce; } @Override protected Object doInBackground(Object... params) { String PROJECT_NUMBER = "puthereprojectnumber"; GoogleCloudMessaging gcm; gcm = GoogleCloudMessaging.getInstance(context); try { regid = gcm.register(PROJECT_NUMBER); Log.v("testing...........", regid); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); } @Override protected void onPostExecute(Object result) { // TODO Auto-generated method stub super.onPostExecute(result); responce.message(regid); } @Override protected void onProgressUpdate(Object... values) { // TODO Auto-generated method stub super.onProgressUpdate(values); } @Override protected void onCancelled(Object result) { // TODO Auto-generated method stub super.onCancelled(result); } @Override protected void onCancelled() { // TODO Auto-generated method stub super.onCancelled(); } } 

`

 `public class GcmBroadcastReceiver extends WakefulBroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { System.out.println("---------------------------" + intent.getDataString()); // Explicitly specify that GcmMessageHandler will handle the intent. ComponentName comp = new ComponentName(context.getPackageName(), GcmMessageHandler.class.getName()); // Start the service, keeping the device awake while it is launching. startWakefulService(context, (intent.setComponent(comp))); setResultCode(Activity.RESULT_OK); } } public class GcmMessageHandler extends IntentService { String mes, ChatID, FromUser, GroupID; private Handler handler; public GcmMessageHandler() { super("GcmMessageHandler"); } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); handler = new Handler(); } @Override protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); // The getMessageType() intent parameter must be the intent you received // in your BroadcastReceiver. String messageType = gcm.getMessageType(intent); mes = extras.getString("title"); ChatID = extras.getString("ChatID"); FromUser = extras.getString("FromUser"); GroupID = extras.getString("GroupID"); // showToast(); shownotification(mes); Log.i("GCM", "Received : (" + messageType + ") " + extras.getString("title")); // GcmBroadcastReceiver.completeWakefulIntent(intent); } @SuppressLint("NewApi") private void shownotification(String message) { NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); SharedPreferences sharedPrefs = getSharedPreferences( Constants.PREFERENCE_NAME, Context.MODE_PRIVATE); if (!T4JTwitterLoginActivity.isConnected(GcmMessageHandler.this)) { Intent showIntent = new Intent(this, SignIn.class); showIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, showIntent, 0); NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder( this).setContentTitle("Reading").setContentText(message) .setDefaults(Notification.DEFAULT_ALL).setAutoCancel(true) .setContentIntent(contentIntent) .setSmallIcon(R.drawable.mainicon); Notification notification = mNotifyBuilder.build(); notification.flags |= Notification.FLAG_AUTO_CANCEL; mNotificationManager.notify(0, notification); } else { ActivityManager activityManager = (ActivityManager) getBaseContext() .getSystemService(Context.ACTIVITY_SERVICE); List<RunningAppProcessInfo> LIST = activityManager .getRunningAppProcesses(); for (RunningAppProcessInfo runningAppProcessInfo : LIST) { String PROSSES = runningAppProcessInfo.processName; System.out.println(PROSSES); } if (sharedPrefs.contains("chatidx")) { System.out.println((sharedPrefs.getString("chatidx", ""))); if (ChatID.equals(sharedPrefs.getString("chatidx", ""))) { } else { callmethood(message); } } else { callmethood(message); } } } void callmethood(String message) { NotificationManager mNotificationManager= (NotificationManager)getSystemService(NOTIFICATION_SERVICE); Intent showIntent = new Intent(this, Send_message.class); SharedPreferences sharedPrefs = getSharedPreferences( Constants.PREFERENCE_NAME, Context.MODE_PRIVATE); Editor e = sharedPrefs.edit(); e.putString("ADMINX", FromUser); e.putString("chatidx", ChatID); e.putString("GID", GroupID); e.commit(); showIntent.putExtra("chatidx", ChatID); showIntent.putExtra("ADMINX", FromUser); showIntent.putExtra("GID", GroupID); showIntent.putExtra("notification", ChatID); showIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, showIntent, 0); NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder( this).setContentTitle("Reading").setContentText(message) .setDefaults(Notification.DEFAULT_ALL).setAutoCancel(true) .setContentIntent(contentIntent) .setSmallIcon(R.drawable.mainicon); Notification notification = mNotifyBuilder.build(); notification.flags |= Notification.FLAG_AUTO_CANCEL; mNotificationManager.notify(0, notification); } public void showToast() { handler.post(new Runnable() { public void run() { Toast.makeText(getApplicationContext(), mes, Toast.LENGTH_LONG) .show(); } }); } } 

`

 `public class GcmBroadcastReceiver extends WakefulBroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { System.out.println("---------------------------" + intent.getDataString()); // Explicitly specify that GcmMessageHandler will handle the intent. ComponentName comp = new ComponentName(context.getPackageName(), GcmMessageHandler.class.getName()); // Start the service, keeping the device awake while it is launching. startWakefulService(context, (intent.setComponent(comp))); setResultCode(Activity.RESULT_OK); } } public class GcmMessageHandler extends IntentService { String mes, ChatID, FromUser, GroupID; private Handler handler; public GcmMessageHandler() { super("GcmMessageHandler"); } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); handler = new Handler(); } @Override protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); // The getMessageType() intent parameter must be the intent you received // in your BroadcastReceiver. String messageType = gcm.getMessageType(intent); mes = extras.getString("title"); ChatID = extras.getString("ChatID"); FromUser = extras.getString("FromUser"); GroupID = extras.getString("GroupID"); // showToast(); shownotification(mes); Log.i("GCM", "Received : (" + messageType + ") " + extras.getString("title")); // GcmBroadcastReceiver.completeWakefulIntent(intent); } @SuppressLint("NewApi") private void shownotification(String message) { NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); SharedPreferences sharedPrefs = getSharedPreferences( Constants.PREFERENCE_NAME, Context.MODE_PRIVATE); if (!T4JTwitterLoginActivity.isConnected(GcmMessageHandler.this)) { Intent showIntent = new Intent(this, SignIn.class); showIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, showIntent, 0); NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder( this).setContentTitle("Reading").setContentText(message) .setDefaults(Notification.DEFAULT_ALL).setAutoCancel(true) .setContentIntent(contentIntent) .setSmallIcon(R.drawable.mainicon); Notification notification = mNotifyBuilder.build(); notification.flags |= Notification.FLAG_AUTO_CANCEL; mNotificationManager.notify(0, notification); } else { ActivityManager activityManager = (ActivityManager) getBaseContext() .getSystemService(Context.ACTIVITY_SERVICE); List<RunningAppProcessInfo> LIST = activityManager .getRunningAppProcesses(); for (RunningAppProcessInfo runningAppProcessInfo : LIST) { String PROSSES = runningAppProcessInfo.processName; System.out.println(PROSSES); } if (sharedPrefs.contains("chatidx")) { System.out.println((sharedPrefs.getString("chatidx", ""))); if (ChatID.equals(sharedPrefs.getString("chatidx", ""))) { } else { callmethood(message); } } else { callmethood(message); } } } void callmethood(String message) { NotificationManager mNotificationManager= (NotificationManager)getSystemService(NOTIFICATION_SERVICE); Intent showIntent = new Intent(this, Send_message.class); SharedPreferences sharedPrefs = getSharedPreferences( Constants.PREFERENCE_NAME, Context.MODE_PRIVATE); Editor e = sharedPrefs.edit(); e.putString("ADMINX", FromUser); e.putString("chatidx", ChatID); e.putString("GID", GroupID); e.commit(); showIntent.putExtra("chatidx", ChatID); showIntent.putExtra("ADMINX", FromUser); showIntent.putExtra("GID", GroupID); showIntent.putExtra("notification", ChatID); showIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, showIntent, 0); NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder( this).setContentTitle("Reading").setContentText(message) .setDefaults(Notification.DEFAULT_ALL).setAutoCancel(true) .setContentIntent(contentIntent) .setSmallIcon(R.drawable.mainicon); Notification notification = mNotifyBuilder.build(); notification.flags |= Notification.FLAG_AUTO_CANCEL; mNotificationManager.notify(0, notification); } public void showToast() { handler.post(new Runnable() { public void run() { Toast.makeText(getApplicationContext(), mes, Toast.LENGTH_LONG) .show(); } }); } } 

`

0
source share

All Articles