Activity starting Broadcast Receiver to check network status - android

I have an activity on which I am initialising a broadcast receiver. I want this broadcast receiver to to call a function in my activity once it has received the message that the network status of the phone has changed.
Unfortunately it seems like the broadcast receiver never receives this message since the onReceive function is never called.
Here the Receiver:
private BroadcastReceiver NetworkReceiver= new BroadcastReceiver() {
#Override
public void onReceive(Context context, 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()) {
Log.d("debug"," in the if");
Handler handler = new Handler();
handler.postDelayed(sendUpdatesToUI, 10);
Log.d("Network Available ", "Flag No 1");
}
}
};
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
update();
}
};
private void update() {
Log.d("debug", "got update");
}
I call register it with this line in the onCreate function:
registerReceiver(NetworkReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
and here is my manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.rtuya.secmere">
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".LoginActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main"
android:theme="#style/AppTheme.NoActionBar" />
</application>
</manifest>
EDIT
I have added this in my manifest but still no result:
<receiver
android:name="NetworkReceiver"
android:label="NetworkReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>

Broadcast receiver also needs to be declared in your manifest.xml
Add
<receiver android:name=".ReceiverName" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
You might want to place receiver in it's own class instead of doing it anonymously.

Don't you have to register receiver in manifest ? Like this:
<receiver
android:name="Receiver"
android:label="Receiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>

Related

Is it possible to Unregister BroadcastReceiver which extends a Class without making Object of it?

I'm using a BroadcastReceiver to check network state which extends a class rather than initializing BroadcastReceiver. So, is it possible to unregister it anywhere?
If yes then how, if not then what would be the alternate solution of doing that.
I see a solution here but it isn't the actual answer of the question.
Here's my class where I am using BroadcastReceiver.
public class CheckNetworkState extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
/*check WIFI state*/
final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
/*check network state*/
final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable() || mobile.isAvailable()) {
//Toast.makeText(context, "connection established", Toast.LENGTH_SHORT).show();
} else {
/*shows dialogue*/
Intent alertDialogueIntent = new Intent(context, DialogueUtils.class);
alertDialogueIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(alertDialogueIntent);
}
}
}
And here's my Manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.hardware.camera" />
<uses-permission android:name="android.hardware.camera.autofocus" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Utils.DialogueUtils" />
<receiver
android:name=".Utils.CheckNetworkState"
android:enabled="true">
<intent-filter>
<action
android:name="android.net.conn.CONNECTIVITY_CHANGE"
tools:ignore="BatteryLife" />
</intent-filter>
</receiver>
<activity android:name=".UserAuth.ChangePassword"></activity>
<activity android:name=".QRScanner.CustomScanner" />
<activity android:name=".WaterMetersList.WaterMeters" />
<activity android:name=".UserAuth.Login" />
<activity
android:name=".ControlCharts.Charts"
android:label="#string/title_activity_bottom_navigation" />
<activity android:name=".Splash">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
In your application class create static receiver as follows:
public class YourApplication extends Application {
public static BroadcastReceiver receiver;
public void onCreate() {
super.onCreate();
receiver = new CheckNetworkState();
}
}
After that you can register your receiver anywhere as:
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
this.registerReceiver(YourApplication.receiver, filter);
After that you can unregister it as:
getContext().unregisterReceiver(YourApplication.receiver);

I am trying to Detecting Incoming Phone Calls In Android

I just want to show a toast when a call is received, But nothing is happening and it doesn't even stop on OnReceive in debugging mode.
I am unable to figure out that why it is not getting stopped at the onReceive. It is just like it is not even receiving an intent .
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.rajatgupta.broadcastrecieverexample">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="MyReciever">
<intent-filter>
<action android:name="rajat_action">
</action>
</intent-filter>
</receiver>
<receiver android:name=".IncomingCall">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE">
</action>
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
IncomingCall.java
public class IncomingCall extends BroadcastReceiver {
Context mContext;
#Override
public void onReceive(Context context, Intent intent) {
try {
Log.d("Intent", "Intent Detected");
Toast.makeText(context," Receiver start ",Toast.LENGTH_SHORT).show();
}
catch (Exception e){
e.printStackTrace();
}
}
}
What am I doing wrong?
It is no longer enough to just to put the READ_PHONE_STATE permission in the Manifest, you now have to request permissions at runtime.
Permission check:
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_PHONE_STATE);
Request:
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_PHONE_STATE},
MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
https://developer.android.com/training/permissions/requesting.html

Android Intent action.MEDIA_SCANNER_FINISHED broadcast

In my application I am trying to receive broadcast Media_Scanner_Finished. But the receiver is not getting called.
Here is my code-
'<?xml version="1.0" encoding="utf-8"?>'
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="objectdistance.ankeshkjaisansaria.ram.sita.MyApp">
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="objectdistance.ankeshkjaisansaria.ram.sita.myApp.broadcastreceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MEDIA_SCANNER_FINISHED"/>
<action android:name="android.intent.action.MEDIA_SCANNER_STARTED"/>
<action android:name="android.intent.action.MEDIA_SCANNER_STARTED"/>
<data android:scheme="file" />
</intent-filter>
</receiver>
</application>
</manifest>
In my Broadcast receiver class:-
public class broadcastreceiver extends BroadcastReceiver {
BroadcastReceiver mMediaScannerReceiver;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i("INFO", "Enter BroadcastReceiver");
}
}
I think the issue is relating to permission required in manifest file to get access to Media_Scanner broadcast.
One more thing I would like to clear is that :- Does Media_Scanner_Started gets called when content provider Media Image database gets updated ?
Add the receiver in code rather than in the manifest:
final IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
filter.addDataScheme("file");
scannerStartedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent intent) {
}
}

Android AlarmManager won't call BroadcastReceiver

I'm trying to call my AlarmReceiver which extends BroadcastReceiver. After I run this code, i can't see any of logs. Could you please help me in this issue. :D
Here's where I try to call AlarmReceiber
public void downloadTweets(Context context) {
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
Intent alarmIntent = new Intent(context,AppService.AlarmReceiver.class);
alarmIntent.putExtra(AppService.SCREEN_NAME, ScreenName);
PendingIntent pi = PendingIntent.getBroadcast(context,0,alarmIntent,PendingIntent.FLAG_UPDATE_CURRENT);//getBroadcast(context, 0, i, 0);
AlarmManager am=(AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Log.v(LOG_TAG, "shot");
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1, pi);
Log.v(LOG_TAG, "shot finish");
} else {
Log.v(LOG_TAG, "No network connection available.");
}
}
and here's my AlarmReceiver class which is a sub-class of AppService
public static class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.v(LOG_TAG, "AlarmReceiver");
Intent sendIntent = new Intent(context,AppService.class);
sendIntent.putExtra(AppService.SCREEN_NAME,intent.getStringExtra(AppService.SCREEN_NAME));
context.startService(sendIntent);
Log.v(LOG_TAG, "AlarmReceiver done");
}
}
And my manifest has this...
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.nutjane.android.rainalert.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>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<service android:name=".service.AppService"/>
<receiver android:name=".service.AppService$AlarmReceiver" android:enabled="true"/>
When I run, the log shows only shot and shot finish
Could you please help me solve this issue.
Add:
sendIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
in your AlarmReceiver class
Change your manifest file to:
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.nutjane.android.rainalert.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>
<service
android:name=".AppService"
android:enabled="true" />
<receiver android:name=".AlarmReceiver" >
<intent-filter>
<action android:name="myintent" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Receiver not registered error when onDestroy function called

When I create class that extends BrodcastReceiver and register it.
Error Unable to destroy activity, Receiver not registered: null onDestroy() function in MainActivity When call unregisterReceiver.
onCreate():
ConnectionChangeReceiver connectionChangeReceiver = new ConnectionChangeReceiver();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(connectionChangeReceiver, filter);
onDestroy():
#Override
protected void onDestroy() {
Log.v("YourActivity", "onDestroy");
unregisterReceiver(connectionChangeReceiver);
super.onDestroy();
}
ConnectionChangeReceiver Class:
public class ConnectionChangeReceiver extends BroadcastReceiver
{
#Override
public void onReceive( Context context, Intent intent )
{
Toast.makeText(context, "CONN", Toast.LENGTH_SHORT).show();
}
}
manifest: UPDATE: After adding <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mamrezo.mapapp" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.mamrezo.mapapp.MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".ConnectionChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
</application>
</manifest>
I always register the receiver in the onStart and unregister it in the onStop. I knew this thanks to this answer : https://stackoverflow.com/a/24391706/1203797
If its still not working in your case, simply wrapunregisterReceiver(connectionChangeReceiver); a try-catch block would be the answer, as stated in the link i posted above.
Or you can register it in the manifest, example :
<receiver android:name=".ConnectionChangeReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>

Categories

Resources