I am working on Alarm Manager. I used a service to start and will ring a tone. But the service is not starting. Can anyone suggest about service, Pending Intent and identify the error in my code. The code is copied from net.
This is my AndroidScheduledActivity.java
public class AndroidScheduledActivity extends Activity {
private PendingIntent pendingIntent;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonStart = (Button) findViewById(R.id.startalarm);
Button buttonCancel = (Button) findViewById(R.id.cancelalarm);
buttonStart.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(AndroidScheduledActivity.this,
MyAlarmService.class);
pendingIntent = PendingIntent.getService(AndroidScheduledActivity.this,
0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
pendingIntent);
Toast.makeText(AndroidScheduledActivity.this, "Start Alarm",
Toast.LENGTH_LONG).show();
Log.d("Alarm", "Alarm Started");
}
});
buttonCancel.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
// Tell the user about what we did.
Toast.makeText(AndroidScheduledActivity.this, "Cancel!",
Toast.LENGTH_LONG).show();
}
});
}
}
And this is my MyAlarmService.java
public class MyAlarmService extends Service {
#Override
public void onCreate() {
// TODO Auto-generated method stub
Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("AlarmService", "Alarm Starting to ring");
Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
MediaPlayer mp = MediaPlayer.create(getBaseContext(), alert);
mp.setVolume(100, 100);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
vibrator.vibrate(400);
Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();
return Service.START_STICKY;
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show();
return super.onUnbind(intent);
}
}
And my menifest.xml file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alarm_basic"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.alarm_basic.AndroidScheduledActivity"
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=".MyAlarmService" />
</application>
</manifest>
Also need to check wheather Ringtone is null also.
Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
Ringtone r = RingtoneManager.getRingtone(getBaseContext(), alert);
if(r == null){
alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
r = RingtoneManager.getRingtone(getBaseContext(), alert);
if(r == null){
alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
r = RingtoneManager.getRingtone(getBaseContext(), alert);
}
}
if(r != null)
r.play();
Or otherway
MediaPlayer mp = MediaPlayer.create(getBaseContext(), alert);
if(mp !=null) {
mp.setVolume(100, 100);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
Intent intent = new Intent(DashboardScreen.this, ServiceClass.class);
PendingIntent pintent = PendingIntent.getService(DashboardScreen.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
Try it, and let me know what happen...
In your manifest.xml file
<service android:enabled="true" android:name=".ServiceClass" />
Add a permission in your Manifest file
< uses-permission android:name="android.permission.VIBRATE" />
Should check vibrator is null or not.
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
if (vibrator != null)
vibrator.vibrate(400);
Related
My App goes like this:
When you first start the app, you'll see a button. Connecting or disconnecting the AC charger doesn't affect anything until you hit that Start button.
When you tap the Start button, the "service" is started.
Now if you remove the AC charger you will hear an alarm sound.
Connecting the AC with the device again should stop the alarm but it does NOT.
Now removing the AC again starts another alarm. The alarms overlap.
Can you help me find the bug?
Thanks
My work so far:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yousef.mustafa.antitheft">
<application
android:allowBackup="true"
android:icon="#mipmap/antitheft"
android:label="#string/app_name"
android:roundIcon="#mipmap/antitheft"
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=".PowerConnectionReceiver">
</receiver>
</application>
</manifest>
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button startServiceButton;
PowerConnectionReceiver powerConnectionReceiver;
BroadcastReceiver powerDisconnectedBroadcastReceiver;
BroadcastReceiver powerConnectedBroadcastReceiver;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
powerConnectionReceiver = new PowerConnectionReceiver(true);
startServiceButton = (ToggleButton) findViewById(R.id.startServiceButton);
powerDisconnectedBroadcastReceiver = new PowerConnectionReceiver(true);
powerConnectedBroadcastReceiver = new PowerConnectionReceiver(false);
startServiceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (startServiceButton.isActivated()) {
unregisterReceiver(powerDisconnectedBroadcastReceiver);
unregisterReceiver(powerConnectedBroadcastReceiver);
Toast.makeText(MainActivity.this, "Service stopped", Toast.LENGTH_SHORT).show();
startServiceButton.setActivated(false);
} else {
monitorBatteryChanges();
}
}
});
}
private void monitorBatteryChanges() {
IntentFilter powerDisconnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_DISCONNECTED");
registerReceiver(powerDisconnectedBroadcastReceiver, powerDisconnectedIntentFilter);
IntentFilter powerConnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_CONNECTED");
registerReceiver(powerConnectedBroadcastReceiver, powerConnectedIntentFilter);
Toast.makeText(MainActivity.this, "Service started", Toast.LENGTH_SHORT).show();
startServiceButton.setActivated(true);
}
}
PowerConnectionReceiver.java
public class PowerConnectionReceiver extends BroadcastReceiver {
MediaPlayer mediaPlayer = new MediaPlayer();
// Determine whether the AC is disconnected or not
private boolean POWER_DISCONNECTED = true;
PowerConnectionReceiver(boolean disconnected) {
this.POWER_DISCONNECTED = disconnected;
}
#Override
public void onReceive(Context context, Intent intent) {
if (POWER_DISCONNECTED) {
mediaPlayer = MediaPlayer.create(context, R.raw.alarm_2);
Toast.makeText(context, "Alarm started", Toast.LENGTH_SHORT).show();
mediaPlayer.start();
mediaPlayer.setLooping(true);
//POWER_DISCONNECTED = false;
} else {
try {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
Toast.makeText(context, "Alarm stopped", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The bug is in your complex code.
You register two different instances of PowerConnectionReceiver one for "connected" and another for "disconnected" events. So MediaPlayer is started in "connected" receiver, and you try to stop MediaPlayer in "disconected", but it doesn't play.
You should remove POWER_DISCONNECTED field, and handle event in a single instance of receiver. You can register a single receiver for multiple events and use intent.getAction() to check how to handle it.
UPD
Also you can make your receiver singleton, to prevent multiple registrations, and playing of multiple MediaPlayers
I was finally able to find a solution.
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button startServiceButton;
BroadcastReceiver powerConnectionBroadcastReceiver;
IntentFilter powerDisconnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_DISCONNECTED");
IntentFilter powerConnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_CONNECTED");
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startServiceButton = (ToggleButton) findViewById(R.id.startServiceButton);
powerConnectionBroadcastReceiver = new PowerConnectionBroadcastReceiver();
startServiceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (startServiceButton.isActivated()) {
unregisterReceiver(powerConnectionBroadcastReceiver);
startServiceButton.setActivated(false);
Toast.makeText(MainActivity.this, "Service stopped", Toast.LENGTH_SHORT).show();
} else {
monitorBatteryChanges();
}
}
});
}
private void monitorBatteryChanges() {
registerReceiver(powerConnectionBroadcastReceiver, powerDisconnectedIntentFilter);
registerReceiver(powerConnectionBroadcastReceiver, powerConnectedIntentFilter);
startServiceButton.setActivated(true);
Toast.makeText(MainActivity.this, "Service started", Toast.LENGTH_SHORT).show();
}
}
PowerConnectionBroadcastReceiver.java
public class PowerConnectionBroadcastReceiver extends BroadcastReceiver {
MediaPlayer mediaPlayer;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
mediaPlayer = MediaPlayer.create(context, R.raw.alarm_1);
mediaPlayer.start();
mediaPlayer.setLooping(true);
Toast.makeText(context, "Alarm started", Toast.LENGTH_SHORT).show();
} else {
try {
if (mediaPlayer != null)
mediaPlayer.release();
Toast.makeText(context, "Alarm stopped", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
It may not be the best solution but it works :)
Thanks for the help.
How can I get the method in my BroadcastReceiver into my Fragment?
Or is it even possible?
receiver:
public class Receiver extends BroadcastReceiver {
public void test(Context c) {
....
}
}
Fragment:
public class Test extends Fragment {
...
}
So a error appeared:
Attempt to invoke virtual method 'android.content.Context
android.content.Context.getApplicationContext()' on a null object
reference
at
com.test.tab.MyReceiver.sendNotificationIfTimeEnd01(MyReceiver.java:47)
at com.test.tab.Juli.broadcastIntent(Juli.java:54)
at com.test.tab.Juli.onCreateView(Juli.java:188)
The code for those lines are:
in Receiver:
public void sendNotificationIfTimeEnd01(Context c) {
Context context = c.getApplicationContext();
Intent intent01 = new Intent(context, MainActivity.class);
....
}
and in Fragment:
receiver.sendNotificationIfTimeEnd01(context);
broadcastIntent();
EDIT UPGRADED CODE:
Fragment:
public class FragmentTest extends Fragment {
private Context context;
IntentFilter filter = new IntentFilter("com.example.Broadcast");
MyReceiver receiver = new MyReceiver();
// Call this method when the condition is met.
public void broadcastIntent() {
Intent intent = new Intent();
intent.setAction("com.example.Broadcast");
getActivity().sendBroadcast(intent);
}
...
if (diffDays <= 0 && diffHours <= 0 && diffMinutes <= 0) {
((TextView) android.findViewById(R.id.test)).setText("test works");
if (!notification043 && !buttonColor01.equals("red01")) {
broadcastIntent();
editor.putBoolean("notification43", true);
editor.apply();
}
}
}
MyReceiver:
public class MyReceiver extends BroadcastReceiver {
public static final int NOTIFICATION_ID_01 = 1;
#Override
public void onReceive(Context context, Intent intent) {
sendNotificationIfTimeEnd01(context);
}
public void sendNotificationIfTimeEnd01(Context c) {
Context context = c.getApplicationContext();
Intent intent01 = new Intent(context, MainActivity.class);
PendingIntent pendingIntent01 = PendingIntent.getActivity(context, 1, intent01, 0);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentIntent(pendingIntent01)
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource(c.getResources(), R.drawable.ic_launcher))
.setContentTitle(testArray[0])
.setContentText("testready")
.setSubText("click here");
NotificationManager notificationManager =
(NotificationManager) c.getSystemService(c.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID_01, builder.build());
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(c.getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Actually, you could use Intents :
public class Test extends Fragment {
...
// Call this method when the condition is met.
public void broadcastIntent() {
Intent intent = new Intent();
intent.setAction("com.example.Broadcast");
getActivity().sendBroadcast(intent);
}
}
And declare that your broadcast receiver can react to this kind of Intent either through the Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.BroadcastDetector"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<receiver android:name="MyReceiver" >
<intent-filter>
<action android:name="com.example.Broadcast" >
</action>
</intent-filter>
</receiver>
</application>
</manifest>
or programmatically
IntentFilter filter = new IntentFilter("com.example.Broadcast");
MyReceiver receiver = new MyReceiver();
getActivity().registerReceiver(receiver, filter);
Then you can intercept this Intent in the receiver :
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
}
}
I want to get data in background and automatic and in the interval of time,
I use this but not work does not work correctly
AndroidManifest.xml
.
.
.
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
.
.
.
<service
android:name=".NewsServiceReceiver"
android:icon="#drawable/ic_launcher"
android:label="#string/service_name" >
</service>
<receiver
android:name=".NewsReceiver"
android:enabled="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<receiver android:name=".NewsStartReceiver" >
</receiver>
NewsReceiver.java
public class NewsReceiver extends BroadcastReceiver {
private static final long REPEAT_TIME = 1000 * 30;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
AlarmManager service = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, NewsStartReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
// start 30 seconds after boot completed
cal.add(Calendar.SECOND, 30);
service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), REPEAT_TIME, pending);
}
}
NewsStartReceiver.java
public class NewsStartReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent service = new Intent(context, NewsServiceReceiver.class);
context.startService(service);
}
}
NewsServiceReceiver.java
public class NewsServiceReceiver extends Service {
.
.
.
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(DBAdapter.TAG, "[*******-----------> BACKGROUND <-----------*******]");
//My Code Here
return Service.START_NOT_STICKY;
}
}
i want run NewsServiceReceiver.java in background when internet connect or app run As well as run automatic in the interval of time!?
my problem solve with
Autostart.java
public class Autostart extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent alarm = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarm, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
System.out.println("[*******-----------> Autostart <-----------*******]");
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 15000, pendingIntent);
}
}
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent background = new Intent(context, NewsServiceReceiver.class);
context.startService(background);
}
}
NewsServiceReceiver.java
public class NewsServiceReceiver extends Service {
private boolean isRunning;
private Context contex;
private Thread backgroundTread;
#Override
public IBinder onBind(Intent intent){
return null;
}
#Override
public void onCreate(){
this.contex = this;
this.isRunning = false;
this.backgroundTread = new Thread(myTask);
}
private Runnable myTask = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("[*******-----------> BACKGROUND <-----------*******]");
//------------My Code Here--------------
stopSelf();
}
};
#Override
public void onDestroy(){
this.isRunning = false;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(!this.isRunning){
this.isRunning = true;
this.backgroundTread.start();
}
return START_STICKY;
}
}
SplashActivity.java -> May first Activity when app run
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
-
this.context=this;
Intent alarm = new Intent(this.context, AlarmReceiver.class);
boolean alarmRunning = (PendingIntent.getBroadcast(this.context, 0, alarm, PendingIntent.FLAG_NO_CREATE) != null);
if(alarmRunning == false){
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.context, 0, alarm, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 15000, pendingIntent);
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
...
<service
android:name=".NewsServiceReceiver"
android:enabled="true" >
</service>
<receiver
android:name=".Autostart"
android:enabled="true"
android:exported="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<receiver android:name=".AlarmReceiver" >
</receiver>
I design alarm manager with repeated in specific time. But when I cancel it on on click method after seconds(time Interval) service start automatically itself.
I want activate service on button click and repeat in interval. and after restaring phone wants to start service too.
any Idea?
here its my manifest code :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alarm"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".AlarmReceiver" android:enabled="true"/>
<receiver android:name=".BootCompleteReceiver" android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<service android:name=".AlarmService" />
</application>
</manifest>
My AlarmReceiver :
public class AlarmReceiver extends BroadcastReceiver {
private static final String TAG = "BANANEALARM";
private static final int NOTIFICATION_ID = 1;
Intent intent;
PendingIntent pendingIntent;
NotificationManager notificationManager;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "starttt", Toast.LENGTH_LONG).show();
// if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Log.d(TAG, "in onreceive");
Intent service1 = new Intent(context, AlarmService.class);
context.startService(service1);
// }
}
}
My BootCompleteReceiver
public class BootCompleteReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Toast.makeText(context, "Boot", Toast.LENGTH_LONG).show();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
this.scheduleAlarms(context, calendar);
}
}
private void scheduleAlarms(Context ctxt, Calendar c) {
AlarmManager alarManager = (AlarmManager) ctxt.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(ctxt, AlarmService.class);
PendingIntent pi = PendingIntent.getService(ctxt, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
alarManager.setRepeating(AlarmManager.RTC,c.getTimeInMillis(),getInterval(), pi);
}
private int getInterval(){
int days = 0;
int hours = 0;
int minutes = 1;
int seconds = 60;
int milliseconds = 1000;
int repeatMS = minutes* seconds * milliseconds;
return repeatMS;
}
}
And my MainActivity :
public class MainActivity extends Activity {
private static final String TAG = "BANANEALARM";
public AlarmManager alarmManager;
Intent alarmIntent;
PendingIntent pendingIntent;
NotificationManager notificationManager;
Button btn,btn2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setAlarm();
}
});
btn2=(Button)findViewById(R.id.stop_s);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopservice();
}
});
}
public void stopservice()
{
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
// Tell the user about what we did.
Toast.makeText(MainActivity.this , "Cancel!", Toast.LENGTH_LONG).show();
}
public void triggerAlarm(View v){
setAlarm();
}
public void setAlarm(){
Intent intent = new Intent(this, AlarmReceiver.class);
intent.setAction("com.example.alarm.ACTION");
PendingIntent pendingIntent = PendingIntent
.getBroadcast(MainActivity.this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
AlarmManager alarm = (AlarmManager) MainActivity.this
.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pendingIntent);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
getInterval(), pendingIntent);
Log.d(TAG,"alarmStartTime: " );
}
private int getInterval(){
int days = 0;
int hours = 0;
int minutes = 1;
int seconds = 60;
int milliseconds = 1000;
int repeatMS = minutes* seconds * milliseconds;
return repeatMS;
}
#Override
protected void onStart(){
super.onStart();
cancelNotifications();
setAlarm();
}
public void cancelNotifications(){
notificationManager.cancelAll();
}
}
In your stopservicemethod, codealarmManager.cancel(pendingIntent), the pendingIntent is always null.
Try replace
PendingIntent pendingIntent = PendingIntent
to
pendingIntent = PendingIntent
in your setAlarm method.
Hope it helps.
I am making app which tracks user location continuously, so far I have been able to make a successful receiving of its ordinate on location change, but if he is restarting the phone than I am not able to start my service without user again opening the app.
This is my Servicesstart.java code
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
Log.i("service started", "start");
userFunctions = new UserFunctions();
final LocationManager locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(userFunctions.isUserLoggedIn(getApplicationContext())){
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
imei=telephonyManager.getDeviceId();
Toast.makeText(getApplicationContext(), imei, 5000).show();
if(Broadcast.check==false)
{
final UserFunctions userFunction = new UserFunctions();
LocationListener locatioListner = new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
get();
}
public void onLocationChanged(Location location) {
Log.i("location", "loc");
String latitude=String.valueOf(location.getLatitude());
String longtitude=String.valueOf(location.getLongitude());
//location updated starts here
boolean check_update=userFunction.locationUpdater(UserFunctions.email, latitude, longtitude,imei);
if(check_update==true){
Log.i("updated", "update");
}
else
{
Log.i("notupdated","not");
}
}
};
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locatioListner);
}
}
}
this is my Broadcast.java code
public class Broadcast extends BroadcastReceiver {
public static boolean check=true;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
check=false;
Intent i = new Intent(context,Servicestart.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(i);
}
}
}
This my manifest.xml code
<service android:name=".Servicestart">
</service>
<receiver android:name=".Broadcast"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Add this permission in manifest and add this broadcast receiver class in your application.
I have added my service ServiceStarter to start first, replace this with yours
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
public class StartupReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent arg1) {
// TODO Auto-generated method stub
System.out.println("Reciver Started..........................................");
Intent activate = new Intent();
activate.setClass(context, **ServiceStarter.class**);
// activate.putExtra("Auto", true);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, activate,
Intent.FLAG_ACTIVITY_NEW_TASK);
AlarmManager mgr = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 20000, pendingIntent);
}
}