network receiver is not working - android

I try to implement the network receiver, here is my following code:
package com.example.androidtablayout;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
public class NetworkReceiver extends BroadcastReceiver { // <1>
public static final String TAG = "NetworkReceiver";
boolean isConnected = true;
Context c;
#Override
public void onReceive(Context context, Intent intent) {
boolean isNetworkDown = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); // <2>
if (isNetworkDown) {
Log.d(TAG, "onReceive: NOT connected, stopping UpdaterService");
// context.stopService(new Intent(context, UpdaterService.class)); // <3>
} else {
Log.d(TAG, "onReceive: connected, starting UpdaterService");
// context.startService(new Intent(context, UpdaterService.class)); // <4>
}
}
}
In the Manifest.xml
<application>
<receiver android:name=".NetworkReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
My problem is when I switch off the wifi, the log still shows that "Connected",
I think the the network receiver didn't receiver the intenet connectivity correctly.Any help will be greatly appreciated.

Here is a sample class that shows you how to do it. I think this is exactly what you need and it might help resolve your issue. In this sample the BroadcastReceiver is registered programmatically instead of the Manifest, but I think it won't be a problem for you.
Let me know if works.

Related

Broadcast receiver is not calling on internet connectivity check

I am trying to make a simple app which will notify if there is internet connection available or not on internet connectivity change. i have found some solution on internet and tries to implement them but somehow its not working. my broadcast receiver which i have registered on my manifest file is not calling on network connectivity change.
Manifest
<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" />
<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=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".NetworkStateChangeReceiver">
<intent-filter >
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
</application>
Broadcast Receiver
package com.gdm.internetconnectivitycheck;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import static android.content.Context.CONNECTIVITY_SERVICE;
public class NetworkStateChangeReceiver extends BroadcastReceiver {
public static final String NETWORK_AVAILABLE_ACTION = "com.gdm.retailalfageek.NetworkAvailable";
public static final String IS_NETWORK_AVAILABLE = "isNetworkAvailable";
#Override
public void onReceive(Context context, Intent intent) {
Intent networkStateIntent = new Intent(NETWORK_AVAILABLE_ACTION);
networkStateIntent.putExtra(IS_NETWORK_AVAILABLE, isConnectedToInternet(context));
LocalBroadcastManager.getInstance(context).sendBroadcast(networkStateIntent);
Log.e("Network Available ", "On receive called");
}
private boolean isConnectedToInternet(Context context) {
try {
if (context != null) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
return false;
} catch (Exception e) {
Log.e(NetworkStateChangeReceiver.class.getName(), e.getMessage());
return false;
}
}
}
Main Activity
package com.gdm.internetconnectivitycheck;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import static com.gdm.internetconnectivitycheck.NetworkStateChangeReceiver.IS_NETWORK_AVAILABLE;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter intentFilter = new IntentFilter(NetworkStateChangeReceiver.NETWORK_AVAILABLE_ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
boolean isNetworkAvailable = intent.getBooleanExtra(IS_NETWORK_AVAILABLE, false);
String networkStatus = isNetworkAvailable ? "connected" : "disconnected";
Snackbar.make(findViewById(R.id.main_activity), "Network Status: " + networkStatus, Snackbar.LENGTH_LONG).show();
}
}, intentFilter);
}
}
Apps targeting Android 7.0 (API level 24) and higher must register the
following broadcasts with
registerReceiver(BroadcastReceiver,IntentFilter)
Declaring a receiver in the manifest does not work.
CONNECTIVITY_ACTION
Beginning with Android 8.0 (API level 26), the
system imposes additional restrictions on manifest-declared receivers.
If your app targets API level 26 or higher, you cannot use the
manifest to declare a receiver for most implicit broadcasts
(broadcasts that do not target your app specifically). You can still
use a context-registered reciever when the user is actively using your
app.
directly from official doc.
you need to register for CONNECTIVITY_CHANGE action at runtime from activity.
using registerReceiver.
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(new NetworkStateChangeReceiver(), filter);
And don't forget to unregister.

AutoStart application on BOOT_COMPLTED unable to start service Intent not found

I am trying to create a Service application without a UI/Activity.
The service will start on BOOT_COMPLETED. Currently I am experiencing an issue when the receiver service cannot start the main service.
The error sound like that (Android Device Monitor):
Tag: Activity Manager
Text: Unable to start service Intent { cmp=com.remote.cat/.ActionService } U=0: not found
My android OS version on the device is 4.2.2
I am testing it via this command in PowerShell:
adb.exe shell am broadcast -a android.intent.action.BOOT_COMPLETED -n com.remote.cat/.AutoStartServiceReceiver
Both services are in the root of the package com.remote.cat
Feel like I am missing a small thing or having a typo, would greatly appreciate any help!
Thank you!
Here is the code of the manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.remote.cat"
android:installLocation="internalOnly">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:allowBackup="true" android:label="#string/app_name"
android:icon="#mipmap/ic_launcher" android:theme="#style/AppTheme">
<receiver android:name="com.remote.cat.AutoStartServiceReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
<service android:name="com.remote.cat.AutoStartServiceReceiver"></service>
<service android:name="com.remote.cat.ActionService"></service>
</manifest>
Here is the brodcastreceiver class:
package com.remote.cat;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AutoStartServiceReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
{
Intent serviceIntent = new Intent(context, ActionService.class);
//Intent serviceIntent = new Intent("com.remote.cat.ActionService");
context.startService(serviceIntent);
}
}
}
Here is the main service that I am trying to start:
package com.remote.cat;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ActionService extends Service
{
private ScheduledThreadPoolExecutor executor = null;
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
executor = new ScheduledThreadPoolExecutor(4);
final ScheduledFuture<?> handle = executor.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "one minute message", Toast.LENGTH_LONG).show();
}
}, 0, 8, TimeUnit.SECONDS);
return START_STICKY;
}
}
Change your AutoStartServiceReceiver declaration in the manifest to be a <receiver> rather than <service>.
The error is in your broadcastreceiver class
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
it should be
if(intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
EDIT
I believe you have to declare your services inside the application tag since it is a part of the application

Detect when cell reception is restored

Reception may be lost as a result of moving out of coverage, switching on the airplane mode or for any other reason. I am not interested in the reason, but I just want to know when reception is restored.
Is there a intent which can be registered to fire up a broadcast receiver?
A connectivity change receiver using android.net.conn.CONNECTIVITY_CHANGE does not seem to work for this purpose.
Any help will be appreciated.
You can use a PhoneStateListener. You do this using a receiver for PHONE_STATE.
In the manifest:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<receiver android:name=".PhoneStateReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
The BroadcastReceiver:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
class PhoneStateReceiver extends BroadcastReceiver {
TelephonyManager telephonyManager;
public void onReceive(Context context, Intent intent) {
ServiceStateListener phoneListener = new ServiceStateListener();
telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_SERVICE_STATE);
}
public void onDestroy() {
telephonyManager.listen(null, PhoneStateListener.LISTEN_NONE);
}
}
The PhoneStateListener:
import android.telephony.PhoneStateListener;
class ServiceStateListener extends PhoneStateListener {
public void onServiceStateChanged (ServiceState serviceState) {
boolean connected = (serviceState.getState() == ServiceState.STATE_IN_SERVICE);
// Do work based on "connected"
}
}

Implementing a service in android.permission.RECEIVE_BOOT_COMPLETED

I take below sample in net searching. I implemented the sample with some modification, but it shows error after rebooting the phone. I also pasting source code i used in the sample, please help me to solve problem
thanks in advance
xml file
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.newtest"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application>
<receiver android:name=".BootCompletedIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name=".BackgroundService"/>
</application>
</manifest>
Broadcast receiver class
package com.example.newtets;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootCompletedIntentReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent pushIntent = new Intent(context, BackgroundService.class);
context.startService(pushIntent);
}
}
}
service class
package com.example.newtets;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class BackgroundService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "OK", Toast.LENGTH_LONG).show();
super.onCreate();
}
}
I dont think you need to compare the intent..
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
.....
}
as, it is captured in the xml file that BootCompletedIntentReceiver should be executed for BOOT_COMPLETED intent.

How to start a service upon device boot up? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Trying to start a service on boot on Android
BroadcastReceiver
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class StartActivityAtBoot extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent i = new Intent(context, CompareIMSI.class);
context.startService(i);
}
}
}
CompareSIM.java
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.widget.Toast;
public class CompareIMSI extends Service{
Context context;
TelephonyManager operator;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
//compareSIM();
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
compareSIM();
}
public void compareSIM(){
final String STORAGE = "Storage";
SharedPreferences unique = getSharedPreferences(STORAGE, 0);
final String storedIMSI = unique.getString("simIMSI", "");
final String currentIMSI = getSubscriberId().toString();
if (!storedIMSI.equals(currentIMSI)){
Intent i = new Intent(CompareIMSI.this, ScreenLockActivity.class);
startActivity(i);
}
}
public String getSubscriberId(){
String IMSI = null;
String serviceName = Context.TELEPHONY_SERVICE;
TelephonyManager m_telephonyManager = (TelephonyManager) getSystemService(serviceName);
IMSI = m_telephonyManager.getSubscriberId();
return IMSI;
}
}
I would like the application to start the compareSIM service upon boot up, during boot up, this service will run as the current attached SIM card IMSI will be retrieved and matched with the already saved IMSI, once they are different the user will be brought to a login layout. I want to perform this during boot up but failed to do so... Kindly advice me on the coding, thanks
floow these steps for stating your service on BOOT:
Step 1: In AndroidManifest.xml add BOOT_COMPLETED permission as:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
Step 2: In AndroidManifest.xml Register your Reciver as:
<receiver android:name=".StartActivityAtBoot" android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
Step 3: In AndroidManifest.xml Register your Service as:
<service android:name=".CompareIMSI"> </service>
Step 3: In StartActivityAtBoot Start your service as:
public class StartActivityAtBoot extends BroadcastReceiver
{
static final String ACTION = "android.intent.action.BOOT_COMPLETED";
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(ACTION))
{
context.startService(new Intent(context,
CompareIMSI.class), null);
Toast.makeText(context, "CompareIMSI service has started!", Toast.LENGTH_LONG).show();
}
}
}
This is all about Starting a Service on Boot.Thanks
You need to register the BroadcastReceiver in the Android manifest, like this:
<receiver android:name=".StartActivityAtBoot">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Also make sure that you have this permission in the manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Check Your androidManifest file. You need to add receiver at androidManifest file.
<receiver android:name=".......StartActivityAtBoot" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>

Categories

Resources