I have tried this code but it's not working. Does anybody have any different solution? I have tried many ways like the below one from Stack Overflow but none of them is working.
manifest.xml
<receiver android:name=".ScreenReceiver">
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF"/>
<action android:name="android.intent.action.SCREEN_ON"/>
</intent-filter>
</receiver>
screenreceiver
public class ScreenReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
{
Intent intent = new Intent();
intent.setClass(context, ScreenLockActivity.class);
startActivity(intent);
}
}
}
To listen to screen on/off, your app should run by time and register Broadcast receiver to OS programmatically.
ScreenOnOffService.java
public class ScreenOnOffService extends Service {
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
super.onCreate();
Log.i("ScreenOnOffService", "onCreate: ");
IntentFilter intentFilter = new IntentFilter();
// intentFilter.addAction("android.intent.action.SCREEN_OFF");
intentFilter.addAction("android.intent.action.SCREEN_ON");
registerReceiver(ScreenOnReceiver.newInstance(), intentFilter);
}
public void onDestroy() {
super.onDestroy();
Log.i("ScreenOnOffService", "onDestroy: ");
unregisterReceiver(ScreenOnReceiver.newInstance());
// startService(new Intent(this,ScreenOnOffService.class));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
}
ScreenOnReceiver.java
public class ScreenOnReceiver extends BroadcastReceiver {
public static final String TAG = "ScreenOn";
public static volatile ScreenOnReceiver screenOn;
public static ScreenOnReceiver newInstance() {
if (screenOn == null) {
screenOn = new ScreenOnReceiver();
}
return screenOn;
}
#Override
public void onReceive(Context context, Intent intent) {
Log.i("hieuN", "intent: " + intent.getAction());
// do work. start activity.
}
}
Start service in activity
Intent service = new Intent(this, ScreenOnOffService.class);
startService(service);
I'm having a really strange issue, the broadcast receiver is not working on my own device but is on the android emulator.
What does my application is restarting the service by calling the broadcast receiver everytime onDestroy method is called.
I even tried to look at developer option on my device to see if the was some restriction activated like "not keep activities", but it was unchecked.
Xml file
<service
android:name="oak.shef.ac.uk.testrunningservicesbackgroundrelaunched.SensorService"
android:enabled="true">
</service>
<receiver
android:name="oak.shef.ac.uk.testrunningservicesbackgroundrelaunched.SensorRestarterBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:label="RestartServiceWhenStopped"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="SensorRestarterBroadcastReceiver" />
</intent-filter>
</receiver>
Service
public class SensorService extends Service {
private Timer timer;
MyThread myThread;
private TimerTask timerTask;
public int counter=0;
public SensorService(Context applicationContext) {
super();
Log.i("HERE", "here I am!");
}
public SensorService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
myThread = new MyThread();
myThread.start();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i("EXIT", "ondestroy!");
Intent restartService = new Intent("SensorRestarterBroadcastReceiver");
sendBroadcast(restartService);
timer.cancel();
myThread.interrupt();
}
public class MyThread extends Thread{
#Override
public void run() {
// TODO Auto-generated method stub
try {
int delay = 10000; // delay for 10 sec.
int period = 10000; // repeat every 10 sec.
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Log.i("in timer", "in timer ++++ "+ (counter++));
}
}, delay, period);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Brodcast Receiver
public class SensorRestarterBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(),
"Restarting Service");
context.startService(new Intent(context, SensorService.class));;
}
}
i want when boot run app server allow for receive message any time
without showing application
this code problem when boot show Notification twice only
but i want receive message any time
Is this "android:exported" important, What used
code AndroidManifest
<service
android:name=".appService"
android:exported="true"
android:enabled="true">
</service>
<receiver
android:name=".ServiceStarterBoot"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
code BroadcastReceiver
public class ServiceStarterBoot extends BroadcastReceiver {
private Context context ;
#Override
public void onReceive(Context context1, Intent intent) {
this.context = context1;
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent serviceLauncher = new Intent(context, appService.class);
context.startService(serviceLauncher);
}}
code Service
public class appService extends Service {
#Override
public void onCreate() {
super.onCreate();
lood();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
//return mBinder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "onStartCommand", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
private void lood(){
SystemClock.sleep(3000);
Runnable runnable = new Runnable() {
public void run() {
boolean p= true ;
while(p) {
SystemClock.sleep(5000);
showNotification();
}
}
};
Thread mythread = new Thread(runnable);
mythread.start();
}
please help
thanks
you have to make your service sticky:
Service.START_STICKY
then it is infinite and restarts itself when killed by OS for any reason.
It even starts itself when booting OS and app is NOT opened by user.
Best regards.
pseudo code:
onStartCommand(..){
...
//e.g. wifilisterner
Wifilistener WF = new Wifilistener(Interface yourInterfaceCallBackMethod);
}
something like this.
I am new android I want to implement in my that when I press power button I need to open the app but the app is killed in the background from recent app tray. I am trying all the solutions which I got but I didnt get solution
MainActivity.class
public class MainActivity extends ActionBarActivity {
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
setContentView(R.layout.activity_main);
/*Toast.makeText(getApplicationContext(),"main Activity run",Toast.LENGTH_SHORT).show();
intent = new Intent(new Intent(getBaseContext(), PowerService.class));
startService(intent);*/
// /* new Handler().post(new Runnable() {
// #Override
// public void run() {
Toast.makeText(getApplicationContext(),"service run",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(new Intent(MainActivity.this, PowerService.class));
startService(intent);
// }
// });
//*/
// Intent notificationIntent = new Intent(this, PowerService.class);
// PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
//
//
//
}
#Override
protected void onStart() {
Toast.makeText(getApplicationContext(),"inside mainactivity onStart",Toast.LENGTH_SHORT).show();
super.onStart();
}
#Override
protected void onResume() {
Toast.makeText(getApplicationContext(),"inside mainactivity onResume",Toast.LENGTH_SHORT).show();
super.onResume();
}
#Override
protected void onRestart() {
Toast.makeText(getApplicationContext(),"inside mainactivity onRestart",Toast.LENGTH_SHORT).show();
super.onRestart();
}
#Override
protected void onDestroy() {
Toast.makeText(getApplicationContext(),"inside mainactivity onDestroy",Toast.LENGTH_SHORT).show();
super.onDestroy();
}
#Override
protected void onStop() {
Toast.makeText(getApplicationContext(),"service run",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(new Intent(MainActivity.this, PowerService.class));
startService(intent);
Toast.makeText(getApplicationContext(),"inside mainactivity onStop",Toast.LENGTH_SHORT).show();
super.onStop();
}
}
Service.class
public class PowerService extends Service {
BroadcastReceiver mReceiver;
IntentFilter filter;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock cpuWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
cpuWakeLock.acquire();
registerReciver();
return Service.START_STICKY;
}
public class LocalBinder extends Binder {
PowerService getService() {
return PowerService.this;
}
}
#Override
public boolean onUnbind(Intent intent) {
System.out.println("inside powerservice onUnbind");
Toast.makeText(getApplicationContext(),"inside powerservice onUnbind",Toast.LENGTH_SHORT).show();
return super.onUnbind(intent);
}
#Override
public void onRebind(Intent intent) {
System.out.println("inside powerservice onRebind");
Toast.makeText(getApplicationContext(),"inside powerservice onRebind",Toast.LENGTH_SHORT).show();
super.onRebind(intent);
}
#Override
public void onStart(Intent intent, int startId) {
System.out.println("inside powerservice onStart");
super.onStart(intent, startId);
}
#Override
public void onDestroy() {
//unregisterReceiver(mReceiver);
//registerReciver();
System.out.println("inside powerservice onDestroy");
Toast.makeText(getApplicationContext(),"inside powerservice ondestroy",Toast.LENGTH_SHORT).show();
startService(new Intent(this, PowerService.class));
super.onDestroy();
}
#Override
public void onTaskRemoved(Intent rootIntent) {
/*registerReciver();
startService(new Intent(this,PowerService.class));*/
Toast.makeText(getApplicationContext(),"inside powerservice onTaskRemoved",Toast.LENGTH_SHORT).show();
/*Intent broadcastIntent = new Intent(this,AppReciever.class);
sendBroadcast(broadcastIntent);
super.onTaskRemoved(rootIntent);*/
/* Intent restartServiceTask = new Intent(this,PowerService.class);
restartServiceTask.setPackage(getPackageName());
PendingIntent restartPendingIntent =PendingIntent.getService(getApplicationContext(), 1,restartServiceTask, PendingIntent.FLAG_ONE_SHOT);
AlarmManager myAlarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
myAlarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartPendingIntent);
startService(new Intent(this,PowerService.class));*/
super.onTaskRemoved(rootIntent);
}
public void registerReciver()
{
filter= new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
filter.addAction(Intent.ACTION_LOCKED_BOOT_COMPLETED);
mReceiver = new AppReciever();
registerReceiver(mReceiver, filter);
}
}
BroadcastReciever
public class AppReciever extends BroadcastReceiver {
public static boolean wasScreenOn = true;
public void onReceive(final Context context, final Intent intent) {
Log.e("LOB", "onReceive");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// do whatever you need to do here
wasScreenOn = false;
Toast.makeText(context,"inside ACTION_SCREEN_OFF",Toast.LENGTH_SHORT).show();
//Log.e("LOB","wasScreenOn"+wasScreenOn);
Log.e("Screen ", "shutdown now");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
Log.e("Screen ", "awaked now");
Toast.makeText(context,"inside ACTION_SCREEN_ON",Toast.LENGTH_SHORT).show();
Intent i = new Intent(context, MainActivity.class); //MyActivity can be anything which you want to start on bootup...
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
} else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
Log.e("LOB", "userpresent");
Toast.makeText(context,"inside ACTION_USER_PRESENT",Toast.LENGTH_SHORT).show();
Intent ii = new Intent(context, MainActivity.class); //MyActivity can be anything which you want to start on bootup...
ii.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(ii);
wasScreenOn = true;
// Log.e("LOB","wasScreenOn"+wasScreenOn);
}
else if(intent.getAction().equals(Intent.ACTION_LOCKED_BOOT_COMPLETED))
{
Toast.makeText(context,"inside ACTION_LOCKED_BOOT_COMPLETED",Toast.LENGTH_SHORT).show();
Log.e("LOB", "userpresent");
Intent ii = new Intent(context, MainActivity.class); //MyActivity can be anything which you want to start on bootup...
ii.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(ii);
}
/* Log.v("##%#%#", "Power button is pressed.");
Toast.makeText(context, "power button clicked",Toast.LENGTH_LONG).show();*/
}
}
Manifestfile
package="com.benayah.app.sampleapp">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.GET_TASKS"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#mipmap/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=".PowerService"
android:enabled="true"
android:exported="false"
android:stopWithTask="false"
android:process=":my_process"
>
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.SCREEN_OFF"></action>
<action android:name="android.intent.action.SCREEN_ON"></action>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"></action>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"></action>
<action android:name="android.intent.action.ACTION_SHUTDOWN"></action>
</intent-filter>
</service>
</application>
Please let me know where I am going wrong in my code and I need to run the service in background to check for the screen on even after the app is killed in background because now when I killed app I couldn't restart my app but if I didn't kill the it is working fine
Use following might be helpfull...
***in Manifest
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".BootCompleteReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
public class BootCompleteReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent intent= new Intent(context, ActivitySample.class);
context.startActivity(intent);
}
}
You below might be helpfull...
In Manifest
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF"></action>
<action android:name="android.intent.action.SCREEN_ON"></action>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"></action>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"></action>
<action android:name="android.intent.action.ACTION_SHUTDOWN"></action>
</intent-filter>
public class MyReceiver extends BroadcastReceiver {
static int countPowerOff=0;
private Activity activity=null;
public MyReceiver (Activity activity)
{
this.activity=activity;
}
#Override
public void onReceive(Context context, Intent intent) {
Log.v("onReceive", "Power button is pressed.");
Toast.makeText(context, "power button clicked", Toast.LENGTH_LONG)
.show();
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
{
countPowerOff++;
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
{
if(countPowerOff==5)
{
Intent i =new Intent(activity,NewActivity.class);
activity.startActivity(i);
}
}
}
And,
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
MyReceiver mReceiver = new MyReceiver (this);
registerReceiver(mReceiver, filter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
The only way i know to monitor the power button is by listening to the ScreenOn and ScreenOff events. So you can try to write a service that is listening to ScreenOn or ScreenOff and then each time that this event is firing you can launch the desired app.
MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, ScreenOnOffService.class);
startService(intent);
}
}
Service:
public class ScreenOnOffService extends Service {
private ScreenOnOffReceiver mScreenReceiver;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
registerScreenStatusReceiver();
}
#Override
public void onDestroy() {
unregisterScreenStatusReceiver();
}
private void registerScreenStatusReceiver() {
mScreenReceiver = new ScreenOnOffReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
registerReceiver(mScreenReceiver, filter);
}
private void unregisterScreenStatusReceiver() {
try {
if (mScreenReceiver != null) {
unregisterReceiver(mScreenReceiver);
}
} catch (IllegalArgumentException e) {}
}
}
Manifest:
<service android:name="com.benayah.app.sampleapp.ScreenOnOffService" />
BroadcastReceiver:
(here you need to put the package name of the app that you want to launch)
in my example i put your package name: com.benayah.app.sampleapp
public class ScreenOnOffReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.d("StackOverflow", "Screen Off");
startApp(context);
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.d("StackOverflow", "Screen On");
startApp(context);
}
}
private void startApp(Context context) {
PackageManager pm = context.getPackageManager();
Intent launchIntent = pm.getLaunchIntentForPackage("com.benayah.app.sampleapp");
context.startActivity(launchIntent);
}
}
I am using
startService(new Intent(getApplicationContext(), NotificationService.class));
from Activity or BroadcastReceiver (using Context context). In every situation, service starts, but with that starts MainActivity also. How to fix it?
Service code:
public class NotificationService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
Manifest:
...
<activity
android:name=".ViewProfileActivity"
android:label="#string/title_activity_view_profile"
android:windowSoftInputMode="adjustResize|stateHidden" >
</activity>
<service
android:name=".NotificationService"
android:process=":NotificationService" >
</service>
...
UPD. Broadcast receiver:
public class BootBroadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, NotificationService.class));
}
}
MainActivity starts from onCreate of Application class.
just replace this code in your MainActivity like this:
startForegroundService(Intent(applicationContext, MyService::class.java));