I am using the following code for alarm, it will alert after 10 secs. Its works fine in emulator but in real device its forcely closing..can you guide me in correct way..
this is my actvity..
public class Alarm1 extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,001000,intent,0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), pendingIntent);
Toast.makeText(this,"Alarm set", Toast.LENGTH_LONG).show();
}
}`
This is receiver class
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm worked", Toast.LENGTH_LONG).show();
try{
Intent back = new Intent(context,Alarm.class);
back.addFlags(Intent.FLAG_FROM_BACKGROUND);
back.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
back.setAction("android.intent.action.MAIN");
back.addCategory("android.intent.category.LAUNCHER");
context.startActivity(back);
}
catch(Exception e){}
}
}
This is to play Ringtone for alarm.
public class Alarm extends Activity {
private MediaPlayer mp; /** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alarm);
mp = MediaPlayer.create(this, R.raw.up);
mp.start();
Button start = (Button) findViewById(R.id.Button01);
start.setOnClickListener(vvvvv);
}
private OnClickListener vvvvv = new OnClickListener() {
public void onClick(View v) {
mp.stop();
finish();
}
};
}
This is working fine in emulator but not on real device..i used permissions also..
I am using Samsung Galaxy 1.6.
Thanks in advance..
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_ONE_SHOT);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND, calendar.get(Calendar.SECOND)+10 );
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),pendingIntent);
Try this, it helped me when I had the same problem
Connect your device, Un-install your app (if installed previously).
Run your application and wait till it gets installed on your phone.
Open Log cat, and now try running your application which according to you force closes, the log cat now shows multiple red and orange lines indicating your errors such has thread handling or low memory etc.
Which would look like this,
Please comment here with your error log, if you require further help.
Related
I want to keep running Alarm Manager at given time interval.
I implement it but doesn't work in proper time period. Sometime its call two times and sometime not call at time of interval.
I used RTC and RTC_WAKEUP and i also want to know what is the meaning of this filed
MainActivity.java
public class MainActivity extends AppCompatActivity {
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = getApplicationContext();
Intent intent = new Intent(this, TestBroadCastReceiver.class);
final PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
final AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
((Button) findViewById(R.id.activity_main_start)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), 2000*60, pi);
Log.d("ALARM MANAGER", "Start Alarm Manager... At " + new Date());
}
});
((Button) findViewById(R.id.activity_main_stop)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alarmManager.cancel(pi);
Log.d("ALARM MANAGER", "Stop Alarm Manager...");
}
});
}
}
AlarmBroadCastReceiver.java
public class TestBroadCastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.e("ALARM MANAGER", "BROADCAST RECEIVER : " + new Date());
}
}
Log
Documentation https://developer.android.com/reference/android/app/AlarmManager.html has an example of BroadcastReceiver, which listens for device awakening.
Starting service from that receiver and schedule next alarm in it.
I've used SharedPreferences for storing next alarm time and starting the same service for handling alarm and scheduling a new one after device boot by passing different keys in start Intent.
As documentation says, RTC won't wake you phone if it is blocked, but RTC_WAKEUP will.
I'm currently working with Android Alarm Manager and found a working example. But it does not work properly in my situation. Let me explain. Basically my goal is to execute a method from the MainActivity each 5 mins. For this purpose I use Alarm Manager to schedule that task.
Basically this is the working stuff:
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.sendBroadcast(new Intent("SERVICE_TEMPORARY_STOPPED"));
}
}
MainActivity.java
public class MainActivity extends Activity{
private PendingIntent pendingIntent;
private AlarmManager manager;
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
registerReceiver(broadcastReceiver, new IntentFilter("SERVICE_TEMPORARY_STOPPED"));
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAlarm();
}
});
}
public void startAlarm() {
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
int interval = 300000;
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Log.d(TAG, "Alarm Set");
}
}
Everything is good. "I'm running" Toast is executed every 300000 ms (5 mins). The AlarmReceiver class send a broadcast to my main Activity with the message "SERVICE_TEMPORARY_STOPPED". I already registered that message in my MainActivity via registerReceiver(broadcastReceiver, new IntentFilter("SERVICE_TEMPORARY_STOPPED"));. But, when I add another method, let's say stopAlarm() in the broadcastReceiver, which is going to stop the alarm after 5 mins, the time interval (5 mins) is not applied anymore. In something like 10 secs, it calls the Broadcast Receiver and stop the alarm. And this is the issue. Take a look at the stop() method and how I call it on the broadcastReceiver:
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
stopAlarm();
}
};
public void stopAlarm() {
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
Log.d(TAG, "Alarm Cancelled");
}
Any clue?
AlarmManager.setRepeating doesn't work properly on different android versions.
Try setExact. It won't repeat but you can achieve repeating functionality as mentioned below:
Updated AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.sendBroadcast(new Intent("SERVICE_TEMPORARY_STOPPED"));
long repeatCount = PreferenceManager.getDefaultSharedPreferences(context).getLong("REPEAT_COUNT", 0L);
repeatCount++;
PreferenceManager.getDefaultSharedPreferences (context).edit().putLong("REPEAT_COUNT", repeatCount).apply()
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
manager.setExact(AlarmManager.RTC_WAKEUP, (repeatCount *System.currentTimeMillis()),pendingIntent);
}
}
Here we maintain a repeatCount & variable (preference based) and increment it in your AlarmReceiver & schedule alarm again by calculating nextAlarmTime using repeatCount * System.currentTimeMillis();
PROBLEM
I want to know some concept to do like the topic said
what should be a requirement to do that
I think that PendingIntent and AlarmManager would be help to restart the service
at time x but I don't know that way to let it call function that I need
Please advice.
FOR EXAMPLE
I have 2 functions in my service class and I want to register it
to run one of these two (Depend on user propose) in the future at time x
SOME CODE THAT I WORK AROUND (EDIT)
public class MyActivity extends Activity implements View.OnClickListener {
private Button b1;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button)findViewById(R.id.cmd1);
b1.setOnClickListener(this);
}
#Override
public void onClick(View view) {
startIntentAt(5,MyReceiver.class);
finish();
}
private void startIntentAt(int seconds, Class<?> c) {
Intent myIntent = new Intent(getBaseContext(), c);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(),0, myIntent, 0);
AlarmManager alarmManager= (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, seconds);
//long interval = 60 * 1000; //
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
public class MyReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Intent scheduledIntent = new Intent(context, TargetActivity.class);
scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scheduledIntent);
}
}
}
What am I doing wrong here? I have setalarm and wakelock in manifest. Im a beginner with Alarm Manager
public class AlarmManagerActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm_manager);
}
public void scheduleAlarm(View V)
{
Intent intentAlarm = new Intent(this, AlarmReceiverActivity.class);
// create the object
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//set the alarm for particular time
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), PendingIntent.getBroadcast(this,1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
}
}
public class AlarmReceiverActivity extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
System.out.println("YO!");
Toast.makeText(context, "Alarm Triggered in ", Toast.LENGTH_LONG).show();
}
}
Please help me, My goal is to update my database with alarm manager every 6 in the morning. It's like reseting a value so I limit the users activity for 1 day
I'll bet you forgot to register the BroadcastReceiver. You need, either, to:
registerReceiver(new AlarmReceiverActivity(), filter);
or, probably better in your case, in the Manifest
<receiver android:name="your.package.AlarmReceiverActivity">
<filter...
</receiver>
I'm just trying to get a simple test app working with AlarmManager.
public class TestActivity extends Activity {
private static final int PERIOD = 1000;
private AlarmManager alarmManager;
private PendingIntent pendingIntent;
#Override
public void onCreate(Bundle savedInstanceState) {
Log.v("TextActivity", "WHY NOT!");
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, TestReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), PERIOD, pendingIntent);
Log.v("TestActivity", "Whee!");
}
}
public class TestReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.v("TestReceiver", "Got Here");
}
}
I have tried this on both a hardware phone and the emulator and I am not seeing the messages received. Am I missing something obvious? I am relatively new to Android development.
Did you register your receiver in AndroidManifest.xml? Also period is milliseconds, so that alarm will trigger every second, is this really what you want?