Initially I had Android 7.0 and didn't have any issues using a BroadcastReceiver and service. However with changes to Android 8.0. I needed to switch to a JobIntentService so my application can run on bootup.
I have tried migrating my code to match the JobIntentService but nothing is happening on bootup.
I am unsure whether the reason is because of my service class or my BroadcastReceiver class.
AndroidManifest.xml
<service android:name=".backgroundService"
android:permission="android.permission.BIND_JOB_SERVICE"/>
backgroundService.java
public class backgroundService extends JobIntentService {
public static final int JOB_ID = 0x01;
public static void enqueueWork(Context context, Intent work) {
enqueueWork(context, backgroundService.class, JOB_ID, work);
}
#Override
protected void onHandleWork(#NonNull Intent intent) {
Toast.makeText(this, "Application and Service Started", Toast.LENGTH_LONG).show();
Intent dialogIntent = new Intent(this, Home.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);
}
}
startOnBoot.java
public class startOnBoot extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null && intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Log.i("In" , "getAction() - Boot");
backgroundService.enqueueWork(context, intent);
}
else
Log.i("No" , "Boot");
}
}
So I am trying to essentially start the Home.class on bootup.
I tried it and it could run normally. You could check three tips below.
1.Check whether you have declared RECEIVE_BOOT_COMPLETED permission or not.
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
2.Check whether you have declared the receiver with BOOT_COMPLETED action.
<receiver android:name=".startOnBoot">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
3.Remove Toast.makeText(this, "Application and Service Started", Toast.LENGTH_LONG).show(); in your service or toast it in main thread. Otherwise it gives you the error java.lang.RuntimeException: Can't toast on a thread that has not called Looper.prepare().
Related
So I have two different apps made, one sends a broadcast and another receives it and displays a toast. However, when I close the receiver app the broadcast is no longer received by the second app even though I defined the receiver in the manifest file.
The broadcast sender in the MainActivity of app1.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button)findViewById(R.id.button2);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setAction("com.example.ali.rrr");
i.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(i);
Log.e("Broadcast","sent");
}
});
}
App 2 broadcast receiver:
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Toast.makeText(context, "Broadcast has been recieved!", Toast.LENGTH_SHORT).show();
Log.e("SUCCESS", "IN RECIEVER");
//throw new UnsupportedOperationException("Not yet implemented");
}
App 2s Manifest:
<?xml version="1.0" encoding="utf-8"?>
<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">
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.example.ali.rrr" />
</intent-filter>
</receiver>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Main2Activity"
android:label="#string/title_activity_main2"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
After registering my BroadcastReceiver (BR) statically in the manifest, applying the proper intent filters, using JobIntentService (and registering it in the manifest) to handle the work that was called from my BR, I was still getting inconsistent results.
Once all of what I listed above has been done you should be able to send an ADB command to activate your broadcast and process the work in your service even if the app is closed. This was working for me some of the time, but not all of the time.
This article describes limitation to BRs.
"As of Android 3.1 the Android system excludes all receiver from receiving intents by default if the corresponding application has never been started by the user or if the user explicitly stopped the application via the Android menu" (AKA a user executes Force Stop)
When I start the app by debugging it, then swipe it closed on my device, my ADB command never activates my BR. However, after my debugging session is over, when I open up the app on my device and swipe it closed, I can activate my BR through ADB commands.
This occurs because when you debug an application, then manually swipe it closed on the device, Android considers this a Force Stop hence why my BR cannot be activated until I re-open the app on the device without debugging.
Scoured the internet for hours, and wasn't able to find my solution, so I thought I'd post it here just in case some poor unfortunate soul is encountering the same weird functionality I was.
Happy coding :)
First of all you need to use the Service for this functionality to work.
In the Activity you can start and stop the service by using the below codes.
// to start a service
Intent service = new Intent(context, MyBrodcastRecieverService.class);
context.startService(service);
// to Stop service
Intent service = new Intent(context, MyBrodcastRecieverService.class);
context.stopService(service);
Then you can use the below service
public class MyBrodcastRecieverService extends Service
{
private static BroadcastReceiver br_ScreenOffReceiver;
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public void onCreate()
{
registerScreenOffReceiver();
}
#Override
public void onDestroy()
{
unregisterReceiver(br__ScreenOffReceiver);
m_ScreenOffReceiver = null;
}
private void registerScreenOffReceiver()
{
br_ScreenOffReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
Log.d(TAG, "ACTION_SCREEN_OFF");
// do something, e.g. send Intent to main app
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(br_ScreenOffReceiver, filter);
}
}
I faced this issue recently. The BroadcastReceiver was working fine even if the app was removed from the background in the emulator and Samsung phones. But it failed to start my app in Chinese manufactured phones like Realme, Mi etc. While struggling to find a way to fix this I found that in the app details page there is battery optimisation settings where the Auto-launch feature was disabled. After I enabled it the app was working fine and BroadcastReceiver was able to start the app. I was unable ti find a way to enable this setting programmatically but I found this question which helped me direct the user to that setting page.
You can go through below solution;
Activity.java
Intent intent=new Intent(MainActivity.this,BroadcastService.class);
startService(intent);
BroadcastService.java
public class BroadcastService extends Service {
private static MusicIntentReceiver br_ScreenOffReceiver;
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public void onCreate()
{
registerScreenOffReceiver();
}
#Override
public void onDestroy()
{
}
private void registerScreenOffReceiver()
{
br_ScreenOffReceiver = new MusicIntentReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("state", -1);
switch (state) {
case 0:
Log.e("AAAAAAAAAA", "Headset is unplugged");
break;
case 1:
Log.e("AAAAAAAAA", "Headset is plugged");
break;
default:
Log.e("AAAAAAAAAAAA", "I have no idea what the headset state is");
}
}
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
registerReceiver(br_ScreenOffReceiver, filter);
}
}
Menifest
<service android:enabled="true" android:name=".BroadcastService" />
Try this way..
Intent i = new Intent();
i.setAction("com.example.ali.rrr");
i.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
i.setComponent(
new ComponentName("PackageNameApp2","PackageNameApp2.MainActivity"));
sendBroadcast(i);
I've an app where the user can call custom lock screen to lock his/her mobile, that is an activity called LockScreen.class.
One this screen is loaded, i.e. the deviced is locked, a SharedPreferences called IsLocked is assigned to be true.
once the user do what he need with tthe lock screen this islocked became false, and the mobile is back to normal.
Every hing is working fine as expected.
The problem is, if for some reason the mobile had been rebooted while the lock screen is active, it is not running back upon a reboot.
So, I created a BootReciever as below, this works fine BUT after having the reboot process completed, and the user can do many things before it is loaded, my question is how can I make it loaded faster? so that the mobile screen is locked again with the custom activity before giving the chance for the user to do anything with the mobile?
public class BootReciever extends BroadcastReceiver
{
SharedPreferences mPrefs;
final String IsLockedPref = "IsLocked";
#Override
public void onReceive(Context context, Intent intent) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Boolean islocked = mPrefs.getBoolean(IsLockedPref, false);
Intent i;
if (islocked)
i = new Intent(context, LockScreen.class);
else
i = new Intent(context, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
part of the manifiest file is:
<receiver android:name=".BootReciever"
android:enabled="true"
android:exported="true">
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
UPDATE
I tried to get use of this by granting Device Admin by adding the below, but nothing improved:
In the main Activity:
private static final int ADMIN_INTENT = 15;
private static final String description = "Some Description About Your Admin";
private DevicePolicyManager mDevicePolicyManager;
private ComponentName mComponentName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDevicePolicyManager = (DevicePolicyManager)getSystemService(
this.DEVICE_POLICY_SERVICE);
mComponentName = new ComponentName(this, AdminReceiver.class);
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mComponentName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,description);
startActivityForResult(intent, ADMIN_INTENT);
.
.
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ADMIN_INTENT) {
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "Registered As Admin", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Failed to register as Admin", Toast.LENGTH_SHORT).show();
}
}
}
and created empty receiver to extend the DeviceAdminReceiver as:
public class AdminReceiver extends DeviceAdminReceiver {
}
and added the below to the manifiest:
<receiver
android:name="AdminReceiver"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data
android:name="android.app.device_admin"
android:resource="#xml/admin"/>
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
One thing you can do from your side is to set a priority to your intent-filter. From documentation
It controls the order in which broadcast receivers are executed to receive broadcast messages. Those with higher priority values are called before those with lower values.
<intent-filter
android:priority="100">
...
</intent-filter>
The value must be an integer, such as "100". Higher numbers have a higher priority. The default value is 0. The value must be greater than -1000 and less than 1000.
I have created a BroadcastReceiver that should listen for the "ACTION_SCREEN_OFF" intent.
public class ExampleReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// run a service..
}
}
I have registered it in the Manifest:
<receiver android:name=".path.to.ExampleReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_SCREEN_OFF"></action>
</intent-filter>
</receiver>
But when the screen is turned off, the onReceive() method is not called. What else do I need to do to get this functionality?
ACTION_SCREEN_OFF is not sent to receivers registered in the manifest. It is only sent to receivers registered via registerReceiver() from a running component.
I am using this to work with Shake, and that works fine for me, but i wanna launch application when user shake their device,
see my code below:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
transcript=(TextView)findViewById(R.id.transcript);
scroll=(ScrollView)findViewById(R.id.scroll);
shaker=new Shaker(this, 1.25d, 500, this);
}
#Override
public void onDestroy() {
super.onDestroy();
shaker.close();
}
public void shakingStarted() {
Log.d("ShakerDemo", "Shaking started!");
transcript.setText(transcript.getText().toString()+"Shaking started\n");
scroll.fullScroll(View.FOCUS_DOWN);
}
public void shakingStopped() {
Log.d("ShakerDemo", "Shaking stopped!");
transcript.setText(transcript.getText().toString()+"Shaking stopped\n");
scroll.fullScroll(View.FOCUS_DOWN);
}
So here is my question, how can i launch an application by shaking my device ?
You should write Android Service that will start your activity during shake. That is all. Services run in the background even if Activity is not visible
Service can be started eg. during device boot. This can be achieved using BroadCastReceiver.
Manifest:
<application ...>
<activity android:name=".ActivityThatShouldBeLaunchedAfterShake" />
<service android:name=".ShakeService" />
<receiver android:name=".BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
BootReceiver:
public class BootReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Intent intent = new Intent(context, ShakeService.class);
context.startService(intent);
}
}
Service:
public class ShakeService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
... somewhere
if(shaked) {
Intent intent = new Intent(getApplicationContext(), ActivityThatShouldBeLaunchedAfterShake.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
Write a separate app for Shake detection. On detection of shake, fire an intent with the package name of app, you want to launch:
Intent intent = new Intent (<PackageNameOfAppToBeLaunched>);
startActivity (intent);
Well What you need is Two different activity Where first One Detects your Shake which need to run all time in background and than call the new actual app you want to run on shake.
You can run your background activity you have to use class which will keep your activity run in background for long time(Continuously) you can use classes Like FutureTask or Executor (you can not use AsyncTask for this).
Whenever the thread passes command to Your Application open after Shake the Background process stops and command goes to app means you need to again immediately start background process after the actual app closed.
You need to write the code to launch the application to foreground from background while the shake started. This link will help you to do so.
I'm trying to set up an alarm receiver right after booting. Therefore, i have an OnBootReceiver that should register the alarm. The onBootReceiver works and it gets called, but somehow it cannot find my AlarmReceiver class.
OnBootReceiver which succesfully starts after booting:
public class OnBootReceiver extends BroadcastReceiver {
private static final String TAG = "OnBootReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "called");
Intent i = new Intent(context, com.packagenames.AlarmReceiver.class);
PendingIntent pi = PendingIntent.getService(context, 0, i, 0);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
time.add(Calendar.SECOND, 30);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), time.getTimeInMillis(), pi);
}
}
As you you can see, it configures the alarm tries to invoke com.packagenames.AlarmReceiver.class. This class exists and is located in the same package:
public class AlarmReceiver extends BroadcastReceiver {
private static final String TAG = "AlarmReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "alarm received");
Intent i = new Intent(context, com.packagename.DataService.class);
i.putExtra("action", "process");
context.startService(i);
}
}
Unfortunately, i get the following error:
02-03 09:22:25.344: W/ActivityManager(103): Unable to start service
Intent { flg=0x4 cmp=com.phonegap.packagename/.AlarmReceiver (has extras)
}: not found
The Android Manifest looks like this
<application>
// activities etc
<receiver
android:name="com.phonegap.packagename.OnBootReceiver"
android:enabled="true"
android:exported="false"
android:label="OnBootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver
android:name="com.phonegap.packagename.AlarmReceiver"
android:enabled="true"
android:label="AlarmReceiver">
<intent-filter>
</intent-filter>
</receiver>
</application>
Do you see a mistake? Maybe I forgot something?
Thanks
edit: in the manifest, I added
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
in order to make the OnBootReceiver work. Do I need something similar for the alarm?
Shouldn't you use getBroadcast instead of getService when creating a pending intent ?
The whole receiver stuff ONLY works if you application is NOT installed on a SD card. Add this to your manifest file to do so:
android:installLocation="internalOnly"