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.
Related
I'm trying to implement an app that allows me to record the audio of calls, activating the service via a toggle button. I can't figure out what is wrong with my code as once I set the toggle button to ON and initiate the call, there is no file saved.
I don't understand if the problem is in saving (maybe I'm looking for the file in the wrong directory?), Or in the fact that it doesn't actually record.
I'm using AndroidStudio 4.0 and i'm trying my app on my Samsung S9.
Thanks in andvance for helping !
RecordService.java
package com.example.registrachiamate;
import android.app.MediaRouteButton;
import android.app.Service;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.format.DateFormat;
import java.io.File;
import java.io.IOException;
import java.util.Date;
public class RecordService extends Service {
private MediaRecorder rec;
private File file;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//return super.onStartCommand(intent, flags, startId);
file= Environment.getExternalStorageDirectory();
Date date=new Date();
CharSequence sdf= DateFormat.format("MM-dd-yy-hh-mm--ss",date.getTime());
rec=new MediaRecorder();
rec.setAudioSource(MediaRecorder.AudioSource.MIC);
rec.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
rec.setOutputFile(file.getAbsolutePath()+"/"+sdf+"rec.3gp");
rec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
TelephonyManager manager=(TelephonyManager) getApplicationContext().getSystemService(getApplicationContext().TELEPHONY_SERVICE);
assert manager != null;
manager.listen(new PhoneStateListener(){
#Override
public void onCallStateChanged(int state, String phoneNumber) {
//super.onCallStateChanged(state, phoneNumber) {
if (TelephonyManager.CALL_STATE_IDLE==state){
rec.stop();
rec.reset();
rec.release();
stopSelf();
}else if(TelephonyManager.CALL_STATE_OFFHOOK==state && rec==null){
try {
rec.prepare();
} catch (IOException e) {
e.printStackTrace();
}
rec.start();
}
}
},PhoneStateListener.LISTEN_CALL_STATE);
return START_STICKY;
}
}
ActivityButton1.java
package com.example.registrachiamate;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.widget.ToggleButton;
import androidx.appcompat.app.AppCompatActivity;
public class ActivityButton1 extends AppCompatActivity {
ToggleButton startandoff;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.button1);
startandoff=(ToggleButton)findViewById(R.id.toggleButton);
}
public void tooglebutton(View view)
{
boolean checked=((ToggleButton)view).isChecked();
if (checked){
Intent intent=new Intent(this,RecordService.class);
startService(intent);
Toast.makeText(getApplicationContext(),"Call Record STARTED",Toast.LENGTH_SHORT).show();
}else {
Intent intent=new Intent(this,RecordService.class);
stopService(intent);
Toast.makeText(getApplicationContext(),"Call Record STOPPED",Toast.LENGTH_SHORT).show();
}
}
}
AndroidManifest.xml, if i put the RecordService, in it stops running
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.registrachiamate">
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<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"
tools:ignore="GoogleAppIndexingWarning">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
<action android:name="android.intent.action.PHONE_STATE"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ActivityButton1"></activity>
<activity android:name=".ActivityButton2"></activity>
<activity android:name=".ActivityButton3"></activity>
<activity android:name=".ActivityButton4"></activity>
<activity android:name=".RecordService"></activity>
</application>
</manifest>
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);
I am new to android stack. I am trying to start android service from the launcher activity. Service and Activity are defined in separate packages but it is not being started. In the logcat there is no exception or error. I have checked many questions on stackoverflow regarding this issue but that didn't worked. Below are the source code of my app. I have spent almost 8 hours on this issue. Any help would be great appreciation.
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nl.test.app">
<supports-screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="true"
android:resizeable="true"
android:smallScreens="true"
android:xlargeScreens="true" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".ui.LoginActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".messaging.AlertService"
android:enabled="true"
android:exported="true">
</service>
</application>
</manifest>
AlertService.java:
package nl.test.app.messaging;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class AlertService extends Service {
public AlertService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(getApplicationContext(), "on create called\n", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
}
LoginActivity.java
package nl.test.app.ui;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;
import nl.test.app.R;
public class LoginActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
// function for service testing
public void onStartButtonClick(View view) {
Intent myIntentToStartAlertListActivity = new Intent();
String pkg = "nl.test.app.messaging";
String cls = "nl.test.app.messaging.AlertService";
myIntentToStartAlertListActivity.setComponent(new ComponentName(pkg, cls));
if (startService(myIntentToStartAlertListActivity) != null) {
Log.i("Service Started","Service started");
Toast.makeText(getApplicationContext(), "Service is running\n", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Service is not running\n", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onStop() {
super.onStop();
}
}
Try this
public void onStartButtonClick(View view) {
Intent myIntentToStartAlertListActivity = new Intent(LoginActivity.this, AlertService.class);
if (startService(myIntentToStartAlertListActivity) != null) {
Log.i("Service Started","Service started");
Toast.makeText(getApplicationContext(), "Service is running\n", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Service is not running\n", Toast.LENGTH_LONG).show();
}
}
// function for service testing
public void onStartButtonClick(View view) {
Intent myIntentToStartAlertListActivity = new Intent(LoginActivity.this,AlertService.class);
String pkg = "nl.test.app.messaging";
String cls = "nl.test.app.messaging.AlertService";
myIntentToStartAlertListActivity.setComponent(new ComponentName(pkg, cls));
//startService(myIntentToStartAlertListActivity)
if (startService(myIntentToStartAlertListActivity) != null) {
Log.i("Service Started","Service started");
Toast.makeText(getApplicationContext(), "Service is running\n", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Service is not running\n", Toast.LENGTH_LONG).show();
}
}
I am making app for me and my class mates, that checks for new homeworks and exams. It has service that may not be killed beacuse of checking school server (like every 5 minutes) for changed size of file with list of exams and stuff like this. I tried following code:
MayinActivity.java
package com.test.simpleservice;
import android.app.ActivityManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//checking runings services - remove later
ActivityManager am = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> rs = am.getRunningServices(50);
String message = null;
for (int i=0; i<rs.size(); i++) {
ActivityManager.RunningServiceInfo
rsi = rs.get(i);
System.out.println("!!!!!!!!!!Service" + "Process " + rsi.process + " with component " + rsi.service.getClassName());
message = message + rsi.process;
}
Button btnStart = (Button) findViewById(R.id.startBtn);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ServiceManager.startService(getApplicationContext());
}
});
}
}
MyServices.java
package com.test.simpleservice;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;
public class MyServices extends Service {
private static final String LOGTAG = "MyServices";
#Override
public void onStart(Intent intent, int startId) {
System.out.println("start...");
//some code of your service starting,such as establish a connection,create a TimerTask or something else
Toast.makeText(this, "service start", Toast.LENGTH_LONG).show();
}
#Nullable
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//this will start service
System.out.println("startcommand...");
Toast.makeText(this, "service startcomand", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
//this will NOT kill service
//super.onDestroy();
Toast.makeText(this, "task destroyed", Toast.LENGTH_LONG).show();
Intent in = new Intent();
in.setAction("PreventKilling");
sendBroadcast(in);
}
#Override
public void onTaskRemoved(Intent intent){
Toast.makeText(this, "task removed", Toast.LENGTH_LONG).show();
intent = new Intent(this, this.getClass());
startService(intent);
}
}
Reciever.java
package com.test.simpleservice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class Receiver extends BroadcastReceiver {
private static final String LOGTAG = "Receiver";
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent serviceIntent = new Intent(context, MyServices.class);
context.startService(serviceIntent);
}
Log.d(LOGTAG, "ServiceDestroy onReceive...");
Log.d(LOGTAG, "action:" + intent.getAction());
Log.d(LOGTAG, "ServiceDestroy auto start service...");
ServiceManager.startService(context);
}
}
ServiceManager
package com.test.simpleservice;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class ServiceManager {
private static final String LOGTAG = "ServiceManager";
public static void startService(Context context) {
Log.i(LOGTAG, "ServiceManager.startSerivce()...");
Intent intent = new Intent(MyServices.class.getName());
intent.setPackage("com.test.simpleservice");
context.startService(intent);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.simpleservice">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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=".MyServices" />
<receiver android:name=".Receiver" >
<intent-filter>
<action android:name="PreventKilling" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.RECIEVE_BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.test.simpleservice.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/start_btn"
android:id="#+id/startBtn"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
When I run the app and click button "start", the service wont start - no toasts, no logs, nothing in setting->apps->services. Why? Any better way to make unkillable process without anoying notification?
logcat
last few lines becouse that before are just listed services:
01-16 14:10:15.567 13753-13772/com.test.simpleservice I/OpenGLRenderer: Initialized EGL, version 1.4
01-16 14:10:15.567 13753-13772/com.test.simpleservice W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
01-16 14:10:15.587 13753-13772/com.test.simpleservice D/OpenGLRenderer: Enabling debug mode 0
01-16 14:10:17.597 13753-13753/com.test.simpleservice I/ServiceManager: ServiceManager.startSerivce()...
And one more question: will this app start after boot? If not, what did I do wrong?
im sorry for my poor english
Intent intent = new Intent(context, MyServices.class);
intent.setPackage("com.test.simpleservice");
context.startService(intent);
Because your context is:
public static void startService(Context context)
And here :
public void onReceive(Context context, Intent intent)
For above Intent name -> intent
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