Why is my Alarm not working? - java

On my Android app I am trying to run a task every 3 minutes, and if the CPU is asleep then it should wake up and run my task; my task is called CheckTask and is a Runnable. I know AlarmManager is what I need and I have been trying to get it working but the OnReceive() method is never executed. Here is the relevant code below, please tell me what is wrong so I can fix it and get it working.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.charles.sitechecker"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="18"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.FLASHLIGHT"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name="com.charles.sitechecker.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=".LocalService"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="com.charles.sitechecker.LocalService" />
</intent-filter>
</service>
<receiver
android:name="com.charles.sitechecker.Alarm"
android:enabled="true"/>
</application>
Alarm.java
package com.charles.sitechecker;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class Alarm extends BroadcastReceiver
{
private MainActivity mainActivity;
private AlarmManager aManager;
public Alarm()
{
}
Alarm(MainActivity mainActivity)
{
this.mainActivity = mainActivity;
aManager = (AlarmManager)mainActivity.getSystemService(Context.ALARM_SERVICE);
}
void scheduleAlarm()
{
Intent intent = new Intent(mainActivity, Alarm.class);
PendingIntent pIntent = PendingIntent.getBroadcast(mainActivity, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
aManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis(), 180000, pIntent);
}
public void onReceive(Context context, Intent intent)
{
Runnable task = new CheckTask(mainActivity);
task.run();
}
}
LocalService.java
package com.charles.sitechecker;
import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
public class LocalService extends Service
{
public void onCreate()
{
Notification n = MainActivity.checkTask.mainActivity.notifier.sendOngoingNotification("SiteChecker", "Sleeping", -1);
startForeground(-1, n);
Alarm alarm = new Alarm(MainActivity.checkTask.mainActivity);
alarm.scheduleAlarm();
}
public void onDestroy()
{
super.onDestroy();
}
public IBinder onBind(Intent intent)
{
return null;
}
public int onStartCommand(Intent intent, int flags, int startId)
{
return START_STICKY;
}
}

an example class to set alarm in mainactivity:
public void setRepeatingAlarm()
{
Intent intent = new Intent(this, ReceiveAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
(*time_in_milis to repeat*), pendingIntent);
}
Broadcast Receiver:
public class ReceiveAlarm extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, InService.class));
}
}
Intent service class example:
public class InService extends IntentService
{
public InService() {
super("InService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
//do your thing here
}
}
Declare your broadcast receiver / service class in manifest inside tags
<receiver android:name="ReceiveAlarm" />
<service android:name="InService"></service>
Try this.

I think you may need to implement a WakeLock. This requires a specific permission, and allows your app to "wake-up" the device to do work.
I used the example referenced in this SO question when I implemented my alarm (many moons ago), and it works well for me.
AlarmManager and WakeLock example
the specific example link is: (from CommonsGuy)
https://github.com/commonsguy/cw-omnibus/tree/master/AlarmManager/Wakeful

Related

Notification not working in Android when using with AlarmManager and Service

I was creating a simple notification app, but which is not showing any notification. I have used BroadcastReceiver and service for showing it up. It doesn't showing any errors but still not working.
MainActivity.java
package com.example.myapplication;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity
{
int NOTIFICATION_REMINDER_NIGHT = 1;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setBroadcast(this);
}
void setBroadcast(Context context)
{
Intent notifyIntent = new Intent(this, MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast
(context, NOTIFICATION_REMINDER_NIGHT, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
1000 * 60 * 15, pendingIntent);
}
}
MyNewIntentService.java
package com.example.myapplication;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentSender;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationManagerCompat;
public class MyNewIntentService extends IntentService
{
private static final int NOTIFICATION_ID = 1;
#Override
public void onCreate() {
super.onCreate();
startForeground(NOTIFICATION_ID, new Notification());
}
/**
* #param name
* #deprecated
*/
public MyNewIntentService(String name) {
super(name);
}
public MyNewIntentService(){
super("service");
}
#Override
protected void onHandleIntent(#Nullable Intent intent)
{
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("My title");
builder.setContentText("This is the body");
builder.setSmallIcon(R.drawable.ic_launcher_background);
Intent notifyIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,2, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
Notification notificationCompat = builder.build();
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(this);
managerCompat.notify(NOTIFICATION_ID, notificationCompat);
}
}
MyReceiver.java
package com.example.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
public class MyReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Intent intent1 = new Intent(context, MyNewIntentService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, MyNewIntentService.class));
} else {
context.startService(new Intent(context, MyNewIntentService.class));
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.MyApplication"
tools:targetApi="31">
<service
android:name=".MyNewIntentService"
android:enabled="true"
android:exported="true"></service>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.lib_name"
android:value="" />
</activity>
<receiver android:name=".MyReceiver"
android:enabled="true"
android:exported="false"/>
</application>
</manifest>
log
android.app.RemoteServiceException:
Bad notification for startForeground
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2275)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:257)
at android.app.ActivityThread.main(ActivityThread.java:8246)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:626)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1016)
what's the problem? is there any os validations.
Thanks.
This error is likely because you're just using an empty notification. Take your logic from onHandleIntent, and use it to construct the notification when calling context.startForeground(...)
Also, AlarmManager::setRepeating is not reliable in modern versions of Android. I would recommend you use setAlarmClock or setExactAndAllowWhileIdle instead.
I have a complete example of an alarm app on my GitHub here, which may be useful for you.

Why My broadcast receiver is not responding to any of the phone state?

Actually, I want a broadcast receiver that can read the phone state like calling, OFFHOOK, idle.
here is my code.
I have added the <uses-permission> for reading Phone State in Manifest file
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Here is my Statically registered Receiver
<receiver android:name=".CallStateBroadcast">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
This is the MainActivity.Java
package com.example.callstateapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
CallStateBroadcast myReceiver = new CallStateBroadcast();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(TelephonyManager.EXTRA_STATE);
registerReceiver(myReceiver,intentFilter);
}
}
This is CallStateBroadcast.Class
package com.example.callstateapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.widget.Toast;
public class CallStateBroadcast extends BroadcastReceiver {
Context mContext;
#Override
public void onReceive(final Context context, Intent intent)
{
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING))
Toast.makeText(context, "Ringing...", Toast.LENGTH_SHORT).show();
if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))
Toast.makeText(context, "Busy...", Toast.LENGTH_SHORT).show();
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE))
Toast.makeText(context, "Free...", Toast.LENGTH_SHORT).show();
}
}
You need to register your receiver class at least once when your application starts. You can add this in your MainActivity.java file and it will work.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CallStateBroadcast myReceiver = new CallStateBroadcast();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(TelephonyManager.EXTRA_STATE);
registerReceiver(myReceiver,intentFilter);
}
CallStateBroadcast.java
public class CallStateBroadcast extends BroadcastReceiver {
Context mContext;
#Override
public void onReceive(final Context context, Intent intent)
{
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
Log.e("Zed", "ringing");
Toast.makeText(context, "Ringing...", Toast.LENGTH_SHORT).show();
}
if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
Log.e("Zed", "offhook");
Toast.makeText(context, "Busy...", Toast.LENGTH_SHORT).show();
}
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
Log.e("Zed", "idle");
Toast.makeText(context, "Free...", Toast.LENGTH_SHORT).show();
}
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<uses-permission android:name="android.permission.READ_PHONE_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=".CallStateBroadcast">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
</application>
Edit
I uploaded my sample project code for you to check. MinSdk version 21, TargetSdk 30.
Here is the recording of working. https://i.stack.imgur.com/wqqqO.gif
To use READ_PHONE_STATE you need:
Note: If both your minSdkVersion and targetSdkVersion values are set to 3 or lower, the system implicitly grants your app this permission. If you don't need this permission, be sure your targetSdkVersion is 4 or higher.
Then, you need to specify:
<uses-sdk
android:minSdkVersion="20"
android:targetSdkVersion="whatyouwant" />

How to open app running in background programmatically

I have an App where a background service running . When a phone call is detected I want that app to open and show me a particular Intent. How should I do this.
My code is
MainActivity.java
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.lang.reflect.Method;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startService(View view){
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateListener phoneStateListener = new PhoneStateListener(){
#Override
public void onCallStateChanged(int state, String incomingNumber) {
String number = incomingNumber;
Log.d("gaandu", number);
if(state == TelephonyManager.CALL_STATE_RINGING){
Toast.makeText(MainActivity.this, "incoming call from" + incomingNumber, Toast.LENGTH_SHORT).show();
}
if(state == TelephonyManager.CALL_STATE_OFFHOOK){
Toast.makeText(MainActivity.this, "Phone is currently in a call", Toast.LENGTH_SHORT).show();
}
if(state == TelephonyManager.CALL_STATE_IDLE){
Toast.makeText(MainActivity.this, "Phone is neither Ringing nor in a Call", Toast.LENGTH_SHORT).show();
}
}
};
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
public void stopService(View view){
Intent i = new Intent(MainActivity.this, MyService.class);
stopService(i);
}
}
MyService.java
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.admin.abab">
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_PHONE_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>
<service android:name=".MyService"
android:exported="false"
/>
</application>
</manifest>
In MainActivity.java, after a phone call has been detected, I want to launch my app running in background to open to its first Activity.
You might want to look into the Android cookbook:
You want to act on an incoming phone call and do something with the incoming number.
Solution:
This can be achieved by implementing a Broadcast receiver and listening for a TelephonyManager.ACTION_PHONE_STATE_CHANGED action.
You probably need to do some more research; depending the version of Android you are targeting!
Try this link. hope this will help you. Transparent your activity will help you some what.
Go through this link also
getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);

Service starts on emulator but on device not

I'am trying to learn how to create services in Android and I've made very simple one.
The problem is that is works like a charm on an AVD but on physical device it is not.
Simply it not starting on boot...
Have a look at the code:
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myservice" android:versionCode="1" android:versionName="1.0">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:icon="#drawable/ic_launcher" android:label="#string/app_name">
<receiver android:name=".ServiceStarter" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:enabled="true" android:name=".MyService" />
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
Service starter:
package com.example.myservice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.example.myservice.MyService;
public class ServiceStarter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())){
Intent pushIntent = new Intent(context, MyService.class);
//pushIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(pushIntent);
}
}
}
and service it self:
package com.example.myservice;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
private static final String TAG = "MyService";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
}
}
I'am running it on android 4.0.3
You need to add an activity to your application, and the user must launch that activity manually first, before your app will function on Android 3.1+. Until that time, your <receiver> will be ignored. I blogged about this ~9 months ago.

Android - Start service on boot

From everything I've seen on Stack Exchange and elsewhere, I have everything set up correctly to start an IntentService when Android OS boots. Unfortunately it is not starting on boot, and I'm not getting any errors. Maybe the experts can help...
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.phx.batterylogger"
android:versionCode="1"
android:versionName="1.0"
android:installLocation="internalOnly">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BATTERY_STATS" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<service android:name=".BatteryLogger"/>
<receiver android:name=".StartupIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
BroadcastReceiver for Startup:
package com.phx.batterylogger;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class StartupIntentReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context, BatteryLogger.class);
context.startService(serviceIntent);
}
}
UPDATE: I tried just about all of the suggestions below, and I added logging such as Log.v("BatteryLogger", "Got to onReceive, about to start service"); to the onReceive handler of the StartupIntentReceiver, and nothing is ever logged. So it isn't even making it to the BroadcastReceiver.
I think I'm deploying the APK and testing correctly, just running Debug in Eclipse and the console says it successfully installs it to my Xoom tablet at \BatteryLogger\bin\BatteryLogger.apk. Then to test, I reboot the tablet and then look at the logs in DDMS and check the Running Services in the OS settings. Does this all sound correct, or am I missing something? Again, any help is much appreciated.
Well here is a complete example of an AutoStart Application
AndroidManifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pack.saltriver" android:versionCode="1" android:versionName="1.0">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<receiver android:name=".autostart">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<activity android:name=".hello"></activity>
<service android:enabled="true" android:name=".service" />
</application>
</manifest>
autostart.java
public class autostart extends BroadcastReceiver
{
public void onReceive(Context context, Intent arg1)
{
Intent intent = new Intent(context,service.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
} else {
context.startService(intent);
}
Log.i("Autostart", "started");
}
}
service.java
public class service extends Service
{
private static final String TAG = "MyService";
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
#Override
public void onStart(Intent intent, int startid)
{
Intent intents = new Intent(getBaseContext(),hello.class);
intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intents);
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
}
}
hello.java - This will pop-up everytime you start the device after executing the Applicaton once.
public class hello extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toast.makeText(getBaseContext(), "Hello........", Toast.LENGTH_LONG).show();
}
}
Following should work. I have verified. May be your problem is somewhere else.
Receiver:
public class MyReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(arg1.getAction())) {
Log.d("TAG", "MyReceiver");
Intent serviceIntent = new Intent(context, Test1Service.class);
context.startService(serviceIntent);
}
}
}
Service:
public class Test1Service extends Service {
/** Called when the activity is first created. */
#Override
public void onCreate() {
super.onCreate();
Log.d("TAG", "Service created.");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("TAG", "Service started.");
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d("TAG", "Service started.");
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test"
android:versionCode="1"
android:versionName="1.0"
android:installLocation="internalOnly">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BATTERY_STATS"
/>
<!-- <activity android:name=".MyActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"></category>
</intent-filter>
</activity> -->
<service android:name=".Test1Service"
android:label="#string/app_name"
>
</service>
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
Your Service may be getting shut down before it completes due to the device going to sleep after booting. You need to obtain a wake lock first. Luckily, the Support library gives us a class to do this:
public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// This is the Intent to deliver to our service.
Intent service = new Intent(context, SimpleWakefulService.class);
// Start the service, keeping the device awake while it is launching.
Log.i("SimpleWakefulReceiver", "Starting service # " + SystemClock.elapsedRealtime());
startWakefulService(context, service);
}
}
then, in your Service, make sure to release the wake lock:
#Override
protected void onHandleIntent(Intent intent) {
// At this point SimpleWakefulReceiver is still holding a wake lock
// for us. We can do whatever we need to here and then tell it that
// it can release the wakelock.
...
Log.i("SimpleWakefulReceiver", "Completed service # " + SystemClock.elapsedRealtime());
SimpleWakefulReceiver.completeWakefulIntent(intent);
}
Don't forget to add the WAKE_LOCK permission:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
I have found a way to make your application run well when the device reboots, please follow the steps below to be successful.
AndroidManifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="pack.saltriver" android:versionCode="1" android:versionName="1.0">
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<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=".UIBootReceiver" android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<service android:name=".class_Service" />
</application>
</manifest>
UIBootReceiver
public class UIBootReceiver extends BroadcastReceiver {
private static final String TAG = "UIBootReceiver";
#Override
public void onReceive(Context context, Intent arg1)
{
Toast.makeText(context, "started", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context,class_Service.class);
context.startService(intent);
}
}
This is asking permission to not need to manage battery saving for this app so you can run in the background stably.
Declare this code in onCreate () of MainActivity class:
Intent myIntent = new Intent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
myIntent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
myIntent.setData(Uri.parse("package:" +
DeviceMovingSpeed.this.getPackageName()));
}
startActivity(myIntent);
Looks very similar to mine but I use the full package name for the receiver:
<receiver android:name=".StartupIntentReceiver">
I have:
<receiver android:name="com.your.package.AutoStart">
I've had success without the full package, do you know where the call chain is getting interrupted? If you debug with Log()'s, at what point does it no longer work?
I think it may be in your IntentService, this all looks fine.
Just to make searching easier, as mentioned in comments, this is not possible since 3.1
https://stackoverflow.com/a/19856367/6505257

Categories

Resources