I have a BroadcastReceiver which checks for NetworkChange, whether connected to Internet or not.
So in my application when the network is disconnected or connected, I want to know which activity has called the BroadcastReceiver, so that I can go back to previous activity after showing an alert informing about the network.
My code,
public class NetworkChangeReceiver extends BroadcastReceiver {
private android.widget.Toast Toast;
#Override
public void onReceive(final Context context, final Intent intent) {
try {
boolean isVisible = MyApplication.isActivityVisible();
Context appContext = context.getApplicationContext();
if (isVisible == true) {
if (checkInternet(context)) {
/*Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);*/
Toast.makeText(context, "Network Available Do operations", Toast.LENGTH_LONG).show();
} else {
Intent i = new Intent(context, NoNetworkAlert.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
Toast.makeText(context, "Network NOT Available Do operations", Toast.LENGTH_LONG).show();
}
.........
......
Here in the above code, when Internet is reconnected,
if (checkInternet(context))I just want to get to the activity which triggered this.
I assume the current activity on the top is the one which triggers the NetworkChangeListener. If so you can use below code snippet,
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
which will give the current Activity on the top.
Do something like this in your activity
BroadcastReceiver br=new NetworkChangeReceiver ();
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
this.registerReceiver(br, filter);
And in your menifest
<receiver
android:name=".NetworkChangeReceiver "
android:exported="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
I have a BroadcastReceiver which checks for NetworkChange, whether connected to Internet or not.
So in my application when the network is disconnected or connected, I want to know which activity has called the BroadcastReceiver, so that I can go back to previous activity after showing an alert informing about the network.
To get the current Activity in Broadcast receiver use the ActivityManager in Broadcast receiver to get the Activity without instance
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
Log.i("ActivityManager ", "ActivityManager" + cn.toString());
To get Activity in the preferred Activity with instance better use Getter and Setter.
MyApplication.Java:
public class MyApplication extends Application {
private Activity mCurrentActivity = null;
// Gloabl declaration of variable to use in whole app
public static boolean activityVisible; // Variable that will check the
// current activity state
public static boolean isActivityVisible() {
return activityVisible; // return true or false
}
public static void activityResumed() {
activityVisible = true;// this will set true when activity resumed
}
public static void activityPaused() {
activityVisible = false;// this will set false when activity paused
}
public Activity getCurrentActivity(){
return mCurrentActivity;
}
public void setCurrentActivity(Activity mCurrentActivity){
this.mCurrentActivity = mCurrentActivity;
}
}
MainActivity.Java:
public class MainActivity extends AppCompatActivity {
private static TextView internetStatus;
protected MyApplication mMyApp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMyApp = (MyApplication) this.getApplicationContext();
internetStatus = (TextView) findViewById(R.id.internet_status);
// At activity startup we manually check the internet status and change
// the text status
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
changeTextStatus(true);
} else {
changeTextStatus(false);
}
}
// Method to change the text status
public void changeTextStatus(boolean isConnected) {
// Change status according to boolean value
if (isConnected) {
internetStatus.setText("Internet Connected.");
internetStatus.setTextColor(Color.parseColor("#00ff00"));
} else {
internetStatus.setText("Internet Disconnected.");
internetStatus.setTextColor(Color.parseColor("#ff0000"));
}
}
#Override
protected void onPause() {
super.onPause();
MyApplication.activityPaused();// On Pause notify the Application
clearReferences();
}
#Override
protected void onResume() {
super.onResume();
MyApplication.activityResumed();// On Resume notify the Application
mMyApp.setCurrentActivity(this);
}
protected void onDestroy() {
clearReferences();
super.onDestroy();
}
private void clearReferences() {
Activity currActivity = mMyApp.getCurrentActivity();
Log.e("Activity", "Activity" + currActivity);
if (this.equals(currActivity))
mMyApp.setCurrentActivity(null);
}
}
InternetConnector_Receiver.Java:
public class InternetConnector_Receiver extends BroadcastReceiver {
public InternetConnector_Receiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
try {
boolean isVisible = MyApplication.isActivityVisible();
Log.i("Activity is Visible ", "Is activity visible : " + isVisible);
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
Log.i("ActivityManager", "Activity Name:" + cn.toString());
// If it is visible then trigger the task else do nothing
if (isVisible == true) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager
.getActiveNetworkInfo();
// Check internet connection and accrding to state change the
// text of activity by calling method
if (networkInfo != null && networkInfo.isConnected()) {
new MainActivity().changeTextStatus(true);
} else {
new MainActivity().changeTextStatus(false);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Manifest Permission:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name="com.internetconnection_demo.MyApplication"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<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>
<!-- Broadcast receiver declaration in manifest file and make sure to enable it -->
<receiver
android:name="com.internetconnection_demo.InternetConnector_Receiver"
android:enabled="true" >
<intent-filter>
<!-- Intent filters for broadcast receiver -->
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
</application>
Related
I am trying to detect internet connectivity using broadcast receiver. I have registered broadcast receiver dynamically but when app launches it is showing error below:
java.lang.IllegalArgumentException: Receiver not registered: com.app.qrius.ConnectivityReceiver#3240fd8
I want to redirect to another activity which shows not network message when there is no internet connection.
Below is my code:
ConnectivityReceiver.java
public class ConnectivityReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo != null){
Toast.makeText(context,"On",Toast.LENGTH_SHORT).show();
}
else{
Intent i = new Intent(context,Network.class);
context.startActivity(i);
((Activity)context).finish();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
protected void onResume() {
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
super.onResume();
}
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Get extra data included in the Intent
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo != null){
Toast.makeText(context,"On",Toast.LENGTH_SHORT).show();
}
else{
// Toast.makeText(context,"Off",Toast.LENGTH_SHORT).show();
Intent i = new Intent(context,Network.class);
context.startActivity(i);
((Activity)context).finish();
}
}
};
}
What am I doing wrong?
You would need to add it to the AndroidManifest.xml
Similar to:
<receiver
android:name=".BatteryPowerBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
<action android:name="android.intent.action.BATTERY_LOW" />
<action android:name="android.intent.action.BATTERY_OKAY" />
<action android:name="android.intent.action.DOCK_EVENT" />
</intent-filter>
</receiver>
You should change your activity as below for programmatically register and unregister broadcast receiver. You can use LocalBroadcastManager for this.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
protected void onResume() {
// Register to receive messages.
// We are registering an observer (mMessageReceiver) to receive
// Intents
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, intentFilter);
super.onResume();
}
#Override
protected void onPause() {
// Unregister since the activity is paused.
LocalBroadcastManager.getInstance(this).unregisterReceiver(
mMessageReceiver);
super.onPause();
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Get extra data included in the Intent
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo != null){
Toast.makeText(context,"On",Toast.LENGTH_SHORT).show();
}
else{
Intent i = new Intent(context,Network.class);
context.startActivity(i);
((Activity)context).finish();
}
}
};
}
For more info, please check
I have a BroadcastReceiver
Manifest
<receiver android:name=".NetworkStateChecker">
<intent-filter >
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"
/>
</intent-filter>
</receiver>
this is the class
public class NetworkStateChecker extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
this.context = context;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI || activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
new AutoTask().execute("start");
}
}
}
}
and when the asynctask is done i call this
context.sendBroadcast(new Intent(act1.DATA_SAVED_BROADCAST));
context.sendBroadcast(new Intent(act2.DATA_SAVED_BROADCAST));
context.sendBroadcast(new Intent(act3.DATA_SAVED_BROADCAST));
here is my sample in one of those activity
public class act1extends AppCompatActivity {
public static final String DATA_SAVED_BROADCAST = "website link";
private BroadcastReceiver broadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
registerReceiver(new NetworkStateChecker(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
//Codes here
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Codes here
}
};
registerReceiver(broadcastReceiver, new IntentFilter(DATA_SAVED_BROADCAST));
}
}
here is the scenario. I will go to an activity do some stuff and return to the activity above after the broadcast receiver works. next is when i go to another activity and do some stuff there after pressing back the broadcast doesnt work
whats the problem? how can i fix it?
I want to check whether Internet connection is turned on or not when app starts. It should allow to start if internet is connected. Else display a error message and direct user to settings. Message need to be displayed until Internet connection is turned on.
Already I finished connection check function and alert display function. How could I listen whether internet is turned on or not after user directed to settings
connection check function is,
public boolean connectionIsAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetwork != null && wifiNetwork.isConnected()) {
return true;
}
NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mobileNetwork != null && mobileNetwork.isConnected()) {
return true;
}
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
return true;
}
return false;
}
and alert display,
public void displayAlertDialog(final Context context){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context, AlertDialog.THEME_TRADITIONAL);
alertDialogBuilder.setMessage("Would you like to enable it?")
.setTitle("No Internet Connection")
.setPositiveButton(" Enable Internet ", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent dialogIntent = new Intent(android.provider.Settings.ACTION_SETTINGS);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(dialogIntent);
}
});
alertDialogBuilder.setNegativeButton(" Cancel ", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
In my onCreate I check like,
if(connectionIsAvailable(getApplicationContext())) {
welcomeThread.start();
} else {
displayAlertDialog(LoadingScreenActivity.this);
}
Help me how could I listen whether internet is turned on or not after user directed to settings. Thanks in advance.
Register receiver in manifest file
<!-- Broadcast receiver declaration in manifest file and make sure to enable it -->
<receiver
android:name=".InternetConnectorReceiver"
android:enabled="true">
<intent-filter>
<!-- Intent filters for broadcast receiver -->
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
Required permissions
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
InternetConnectorReceiver.class
public class InternetConnectorReceiver extends BroadcastReceiver {
// you can perform the action based on InternetConnected or not based on value of this variable.
public static boolean IsInternetConnected = true;
public InternetConnectorBroadcastReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
try {
boolean isVisible = NameOfapplicationclass.isActivityVisible();
// If it is visible then trigger the task else do nothing
if (isVisible == true) {
if (isInternetConnected(context)) {
IsInternetConnected = true;
}
else
{
IsInternetConnected = false;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static boolean isInternetConnected(Context context) {
ConnectivityManager cmObj = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cmObj.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
return true;
}
return false;
}
Add Following code in application class
public static boolean activityVisible;
public static boolean isActivityVisible() {
return activityVisible; // return true or false
}
public static void activityResumed() {
activityVisible = true;// this will set true when activity resumed
}
public static void activityPaused() {
activityVisible = false;// this will set false when activity paused
}
You have to use BroadcasrReceive
try this.
Create class for BroadcastReceiver
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
//Do your code
}
}
and register it in manifest file like this
<receiver android:name=".NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--Custom Broadcast Receiver for checking Internet Connectivity-->
<receiver
android:name=".extras.ConnectivityReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<!--End-->
Connectivity Receiver Class:
public class ConnectivityReceiver extends BroadcastReceiver {
public static ConnectivityReceiverListener connectivityReceiverListener;
public ConnectivityReceiver() {
super();
}
#Override
public void onReceive(Context context, Intent arg1) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null
&& activeNetwork.isConnectedOrConnecting();
if (connectivityReceiverListener != null) {
connectivityReceiverListener.onNetworkConnectionChanged(isConnected);
}
}
/**
* Checking if internet connection is active or not
* #return
*/
public static boolean isConnected() {
ConnectivityManager
cm = (ConnectivityManager) MyApplication.getInstance().getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null
&& activeNetwork.isConnectedOrConnecting();
}
public interface ConnectivityReceiverListener {
void onNetworkConnectionChanged(boolean isConnected);
}
}
Activity Code:
public class HomeActivity extends AppCompatActivity
implements ConnectivityReceiver.ConnectivityReceiverListener {
/**
* Callback will be triggered when there is change in
* network connection
*/
#Override
public void onNetworkConnectionChanged(boolean isConnected) {
if (!isConnected) {
// show dialog \\
} else {
// check if dialog is visible \\
// if visible then dismiss else do your stuff \\
}
}
#Override
protected void onResume() {
super.onResume();
// Register connection status listener \\
MyApplication.getInstance().setConnectivityListener(this);
}
}
My Application class code and set it in manifest:
public class MyApplication extends Application {
private static MyApplication mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
//-------Broadcast Receiver for Checking Internet Connection----------\\
public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener) {
ConnectivityReceiver.connectivityReceiverListener = listener;
}
//----------------------------------------------------------------------\\
}
When phone's network status changed, it will send a broadcast. So you just need a BroadcastReceiver.
For more detail check official documentation
I've checked this example of how to handle network connectivity changes:
Android Check Internet Connection and found a very nice piece of code of how to handle this changes:
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
String status = NetworkUtil.getConnectivityStatusString(context); //some internal class to determinate which type is connected
Toast.makeText(context, status, Toast.LENGTH_LONG).show();
}
}
To make this thing work I need to declare this BroadcastReceiver inside my manifest file:
<application ...>
...
<receiver
android:name="net.viralpatel.network.NetworkChangeReceiver"
android:label="NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
...
</application>
Now I want to update UI, when wifi/mobile data is connected.
I can either make the NetworkChangeReceiver class inner static or external. But what I need is that I can work with my MainActivity UI from public void onReceive. How I can do this?
The answer was easy. I don't need to register my broadcast in order to get broadcast about connectivity change:
private BroadcastReceiver networkConnectivityReciever = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
NetworkInfo currentNetworkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (dialog != null) {
if(currentNetworkInfo.isConnected()){
dialog.dismiss();
webView.reload();
}else{
dialog.show(((MainActivity) context).getSupportFragmentManager(), "");
}
}
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(networkConnectivityReciever,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(networkConnectivityReciever);
}
And only thing I need in manifest is this:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I am creating sample app with kiosk mode in my app to check that is kiosk mode work or not.?. But in sample app kiosk mode is not working. I means after screen goes off activity is not starting.
I have taken this from [http://www.andreas-schrade.de/2015/02/16/android-tutorial-how-to-create-a-kiosk-mode-in-android/][here]
THis is my main activity
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(!hasFocus) {
// Close every kind of system dialog
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeDialog);
}
}
}
THis is my Application class
public class AppContext extends Application {
private AppContext instance;
private PowerManager.WakeLock wakeLock;
private OnScreenOffReceiver onScreenOffReceiver;
PowerManager pm;
#Override
public void onCreate() {
super.onCreate();
instance = this;
registerKioskModeScreenOffReceiver();
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
startKioskService();
}
private void registerKioskModeScreenOffReceiver() {
// register screen off receiver
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
onScreenOffReceiver = new OnScreenOffReceiver();
registerReceiver(onScreenOffReceiver, filter);
}
public PowerManager.WakeLock getWakeLock() {
if(wakeLock == null) {
// lazy loading: first call, create wakeLock via PowerManager.
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "wakeup");
}
return wakeLock;
}
private void startKioskService() { // ... and this method
startService(new Intent(this, KioskService.class));
}
}
This is receiver class
public class OnScreenOffReceiver extends BroadcastReceiver {
private static final String PREF_KIOSK_MODE = "pref_kiosk_mode";
#Override
public void onReceive(Context context, Intent intent) {
if(Intent.ACTION_SCREEN_OFF.equals(intent.getAction())){
AppContext ctx = (AppContext) context.getApplicationContext();
// is Kiosk Mode active?
if(isKioskModeActive(ctx)) {
wakeUpDevice(ctx);
}
}
}
private void wakeUpDevice(AppContext context) {
PowerManager.WakeLock wakeLock = context.getWakeLock(); // get WakeLock reference via AppContext
if (wakeLock.isHeld()) {
wakeLock.release(); // release old wake lock
}
// create a new wake lock...
wakeLock.acquire();
// ... and release again
wakeLock.release();
}
private boolean isKioskModeActive(final Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getBoolean(PREF_KIOSK_MODE, false);
}
}
THis is Service class
public class KioskService extends Service {
private static final long INTERVAL = TimeUnit.SECONDS.toMillis(2); // periodic interval to check in seconds -> 2 seconds
private static final String TAG = KioskService.class.getSimpleName();
private static final String PREF_KIOSK_MODE = "pref_kiosk_mode";
private Thread t = null;
private Context ctx = null;
private boolean running = false;
#Override
public void onDestroy() {
Log.i(TAG, "Stopping service 'KioskService'");
running =false;
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Starting service 'KioskService'");
running = true;
ctx = this;
// start a thread that periodically checks if your app is in the foreground
t = new Thread(new Runnable() {
#Override
public void run() {
do {
handleKioskMode();
try {
Thread.sleep(INTERVAL);
} catch (InterruptedException e) {
Log.i(TAG, "Thread interrupted: 'KioskService'");
}
}while(running);
stopSelf();
}
});
t.start();
return Service.START_NOT_STICKY;
}
private void handleKioskMode() {
// is Kiosk Mode active?
if(isKioskModeActive(ctx)) {
// is App in background?
if(isInBackground()) {
restoreApp(); // restore!
}
}
}
private boolean isInBackground() {
ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
return (!ctx.getApplicationContext().getPackageName().equals(componentInfo.getPackageName()));
}
private void restoreApp() {
// Restart activity
Intent i = new Intent(ctx, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(i);
}
public boolean isKioskModeActive(final Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getBoolean(PREF_KIOSK_MODE, false);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
This is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.kioskmode"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:name=".AppContext"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<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>
<service android:name="com.example.kioskmode.KioskService" android:exported="false"></service>
<receiver android:name="com.example.kioskmode.OnScreenOffReceiver" android:enabled="true" >
<intent-filter android:priority="1000" >
<action android:name="android.app.action.SCREEN_OFF" />
<action android:name="android.app.action.SCREEN_ON" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.GET_TASKS"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</manifest>
Any one can solve this... for me..?? Thanks in advance..
Your method isKioskModeActive is always false. So it won't restore your app.