i was trying to create my own alarm clock in android. The aim is that my alarm clock should play different songs based on my playlist . This is a college project . User sets an alarm and then forgets and then even after multiple restarts the alarm should play . I downloaded a sample code from and was working on this . However on a restart of phone my alarms are getting lost . I found that i need to use broadcast receiver but still its not working on my phone lava phone . Can you please suggest if this code is fine . Here is my code link:https://drive.google.com/file/d/1ADVyH0grEQ4g80HkFU1n2Cb4wxnQC4TX/view?usp=sharing
my android manifest file is..
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.alarmmanager">
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<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="MyBroadcastReceiver" >
</receiver>
</application>
</manifest>
my layout file...
<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"
tools:context=".MainActivity" >
<EditText
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="28dp"
android:ems="10"
android:hint="Number of seconds"
android:inputType="numberDecimal" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/time"
android:layout_below="#+id/time"
android:layout_marginRight="60dp"
android:layout_marginTop="120dp"
android:text="Start" />
</RelativeLayout>
my receiver code..
package com.alarmmanager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.util.Log;
import android.widget.Toast;
import java.util.Calendar;
/**
* Created by bhaskar on 24-04-2018.
*
*/
public class MyBroadcastReceiver extends BroadcastReceiver {
MediaPlayer mp;
#Override
public void onReceive(Context context, Intent intent) {
mp= MediaPlayer.create(context, R.raw.alrm );
mp.start();
Toast.makeText(context, "Alarm....", Toast.LENGTH_LONG).show();
Log.i("Alarm","Alarm"+ Calendar.getInstance().getTime());
}
}
mainActivity file
public class MainActivity extends AppCompatActivity {
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startAlert();
}
});
}
public void startAlert() {
EditText text = (EditText) findViewById(R.id.time);
int i = Integer.parseInt(text.getText().toString());
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (i * 1000), pendingIntent);
Toast.makeText(this, "Alarm set in " + i + " seconds", Toast.LENGTH_LONG).show();
}
}
see this official doc for maintaining alarm when phone gets restarted.
in Start an Alarm When the Device Boots section
After getting the actual code i am editing this answer :
1) create new Receiver instead of using old one receiver
public class SampleBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
// Set the alarm here.
Log.d("AlarmDone", "AlarmDone");
}
}
}
2) register it in manifest file :
<receiver
android:name=".SampleBootReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
3) change your old receiver code in menifest :
<receiver android:name=".AlarmReceiver" />
Note : add permission in manifest
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
now your alarm will ring.
For me it works only when i enable auto start
Related
I am trying to make broadcast receiver which will show a toast message when user click on button from my another app activity.
But receiver not showing result.
My code is below
My Receiver App
MyReceiver:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Broadcast has been received!", Toast.LENGTH_LONG).show();
}
}
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.xyz.receivebroadcast">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.example.xyz.broadcasts"></action>
</intent-filter>
</receiver>
</application>
My sender app
My MainActivity which sends the broadcasts is here.
MainActivity:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void SendOutBroadcast(View view){
Intent i = new Intent();
i.setAction("com.example.xyz.broadcasts");
i.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
sendBroadcast(i);
}
}
activity_main.xml:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.xyz.broadcasts.MainActivity">
<Button
android:id="#+id/sendButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="SendOutBroadcast"
android:text="Send Broadcast"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
In your case your activity Intent should be like this:
Intent intent = new Intent();
intent.setAction("com.example.xyz.broadcasts");
intent.putExtra("KeyName","code1id");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
intent.setComponent(
new ComponentName("com.pkg.AppB","com.pkg.AppB.MainActivity"));
sendBroadcast(intent);
Try this may help you or visit for more information.
NOTE - This may be not going to work in Android O because in Android O implicit broadcast are ban as mentioned Here. (Also credits to you #Muhammad Arslan Maqsood)
i found the issue: issue is not with code, actually Android O disabled the feature "Implicit broasdcast". see this
I am simply trying to implement the AlarmManager. I wrote the code for alarm manager but the code doesnot work. AlarmManager doesnot fire the Broadcast Receiver and service. But when I donot use the AlarmManager and simply start the service using intent the service run. How to make AlarmManager work to schedule the service periodically?
Below is the code:
MainActivity.java
package com.alarmmanager;
import android.app.*;
import android.os.Bundle;
import android.content.*;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this,AlarmReceiver.class);
PendingIntent pending =PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm =(AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),15000,pending);
}
}
AlarmReceiver.java
package com.alarmmanager;
import android.content.*;
public class AlarmReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
intent =new Intent(context,MainService.class);
context.startService(intent);
}
}
MainService.java
package com.alarmmanager;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MainService extends Service
{
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
Log.i("nilavs","nilav");
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.alarmmanager"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="23" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<service
android:name=".MainService"
android:enabled="true"
/>
<activity
android:name=".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>
<receiver android:process=":remote" android:name=".AlarmReceiver">
</receiver>
</application>
</manifest>
You should use getBroadcast instead of getService?
PendingIntent pending =PendingIntent.getService(this, 0, intent, 0);
Edit:
Try setting it to fire off in the future initially - e.g.
alarm.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+5000,15000,pending);
I am coding a simple alarm test in android, but as mentionned in the title the AlarmReceiver isn't triggered !
i sought here for the solution but none of them worked since my code seems to be correct ...
here is my code :
public class AlarmActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
Button salarm = (Button) findViewById(R.id.salarm);
final AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent i = new Intent(AlarmActivity.this,AlarmReceiver.class);
final PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0, i, 0);
salarm.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
alarmManager.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime()+(1000*5), pi);
Toast.makeText(getApplicationContext(), "Alarm set, wait 5 sec", Toast.LENGTH_SHORT).show();
}
});
}
Manifest file :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidtest3"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.androidtest3.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>
<activity android:name="AlarmActivity"/>
<receiver
android:exported = "true"
android:name = "AlarmReceiver">
</receiver> <!-- <receiver android:name="AlarmReceiver"/> aurait fait l'affaire -->
</application>
</manifest>
AlarmReceiver Class :
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "pending intent received !", Toast.LENGTH_SHORT).show();
}
}
it would help if you could explain the any solution you suggest.
thanx
It's likely not happening because the time value is incorrect. If you are going to use RTC_WAKEUP type alarms, get the time using System.currentTimeMillis() plus your additional time. Right now you're using elapsed time, which is not the same as RTC wall clock time.
I am trying to use an alarm manager with BroadcastReceiver. I try to use the example given in Tutorial: System Services and BroadcastReceiver . but when I run the example after the end of the time the toast doesn't show up. the code is below:
My main Activity:
public class AlarmActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
}
public void startAlert(View view) {
EditText text = (EditText) findViewById(R.id.time);
int i = Integer.parseInt(text.getText().toString());
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (i * 1000), pendingIntent);
Toast.makeText(this, "Alarm set in " + i + " seconds",
Toast.LENGTH_LONG).show();
}
}
my broadCastReceiver:
public class MyBroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Don't panic but your time is up!!!!.",
Toast.LENGTH_LONG).show();
// Vibrate the mobile phone
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
}
}
my main Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Number of seconds"
android:inputType="numberDecimal" >
</EditText>
<Button
android:id="#+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startAlert"
android:text="Start Counter" >
</Button>
</LinearLayout>
and the manifestfile:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcastreceiver"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.VIBRATE" >
</uses-permission>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.broadcastreceiver.AlarmActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.example.android_alarm.MyBroadcastReceiver" >
</receiver>
</application>
</manifest>
The receiver must extend from BroadcastReceiver
public class MyBroadcastReceiver extends BroadcastReceiver {
// ...
}
Also be sure that receiver name in manifest file is correct.
Your MyBroadcastReceiver class is wrong, edit your MyBroadcastReceiver class to the following:
public class MyBroadcastReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Don't panic but your time is up!.",
Toast.LENGTH_LONG).show();
// Vibrate the mobile phone
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
}
}
You need to add extends BroadcastReceiver and override onReceive() method.
You just forgot to override OnReceive() method. public void onReceive(Context context, Intent intent) is predefined method of BroadcastReceiver, wheneven you are using it, You must #Override it as follows,
public class MyBroadcastReceiver extends BroadcastReceiver
{
#Override // You forgot this line
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Don't panik but your time is up!!!!.",Toast.LENGTH_LONG).show();
}
}
You have created a startAlert function which u didn't call anywhere.So first call that method in onCreate and then you will receive a toast.
So i'm setting a repeating alarm to fetch data from a server. The problem is that nothing happens when the alarm is suppose to go off. I get no errors while launching it, and the code is correct (as far as i know).
Here is the code that sets the alarm:
private void startRequestTimer() {
// This is what will be called when the alarm goes off (GetOperations)
Intent intent = new Intent(MainActivity.this, GetOperations.class);
PendingIntent operation = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
// The alarm will go off in one second from now
long firstTime = SystemClock.elapsedRealtime();
firstTime += 1000;
// Set the alarm
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 5*1000, operation);
}
Here is GetOperations.java (it's called when the alarm goes off)
package se.jbhalmstad.ndroid;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class GetOperations extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Oh! The alarm went off!", 2000).show();
}
}
And the manifest, in case i messed something up here (which i doubt, since i'm not getting any errors):
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="se.jbhalmstad.ndroid"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />
<application android:icon="#drawable/icon" android:label="#string/APP_NAME">
<activity android:name=".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>
<activity android:name=".SettingsActivity" />
<activity android:name=".GetOperations" />
</application>
</manifest>
Have i missed something?
You declared GetOperations as a BroadcastReceiver, but in your Manifest it's an Activity.