I have been trying to slowly learn the Android API over the past month. I have read documentation, viewed examples and can't seem to figure out what I'm doing incorrectly. Basically the app sets an alarm 1 minute exactly after the app was started.
The issue I am currently having is after setting an alarm, it isn't being received. Here's what I have:
SetAlarmActivity.java
public class SetAlarmActivity extends AppCompatActivity {
private final String TAG = "AlarmTest";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_alarm);
Calendar c = Calendar.getInstance();
c.add(Calendar.MINUTE, 1);
Log.d(TAG, "Alarm time is " + c.getTime());
// set the intent to launch our SetAlarmActivity
Intent alarmIntent = new Intent(SetAlarmActivity.this, SetAlarmActivity.class);
// retrieve a PendingIntent to perform a Broadcast
PendingIntent pendingAlarmIntent = PendingIntent.getBroadcast(SetAlarmActivity.this, 0, alarmIntent, 0);
// grab the Alarm Service and tell it to call our Intent at the set time
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingAlarmIntent);
}else{
alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingAlarmIntent);
}
}
}
AlarmReceiver.java
public class AlarmReceiver extends WakefulBroadcastReceiver {
private final String TAG = "AlarmTest";
#Override
public void onReceive(Context context, Intent intent){
Log.d(TAG, "Received broadcast!");
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="bz.bdu.alarmtest" >
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name=".SetAlarmActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".AlarmReceiver" />
</application>
</manifest>
You have to create the intent between the Current activity and receiver class. change your code like this.
Intent intent = new Intent(SetAlarmActivity.this, AlarmReceiver.class);
change
Intent alarmIntent = new Intent(SetAlarmActivity.this,
SetAlarmActivity.class);
to
Intent alarmIntent = new Intent(SetAlarmActivity.this,
AlarmReceiver.class);
then its works fine
Related
I have an alarm clock app. When I create an alarm, it works well (If you do not exit the application), but if you exit, then the alarm does not work.
I want the alarm to work even when the application is turned off and the phone is in sleep mode. Here is my code:
AlarmFragment (From which the alarm is set):
package org.vitaliy.numbell.Fragments;
public class AlarmFragment extends Fragment {
ImageButton add_btn;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_alarm, container, false);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
add_btn = view.findViewById(R.id.add_btn);
add_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar cur_time = Calendar.getInstance();
MaterialTimePicker materialTimePicker = new MaterialTimePicker.Builder()
.setTimeFormat(TimeFormat.CLOCK_24H)
.setHour(cur_time.get(Calendar.HOUR_OF_DAY))
.setMinute(cur_time.get(Calendar.MINUTE))
.build();
materialTimePicker.addOnPositiveButtonClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onClick(View view) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.MINUTE, materialTimePicker.getMinute());
calendar.set(Calendar.HOUR_OF_DAY, materialTimePicker.getHour());
//Set alarm clock
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(ALARM_SERVICE);
AlarmManager.AlarmClockInfo alarmClockInfo = new AlarmManager.AlarmClockInfo(calendar.getTimeInMillis(), getAlarmInfoPendingIntent());
alarmManager.setAlarmClock(alarmClockInfo, getAlarmActionPendingIntent());
}
});
materialTimePicker.show(getActivity().getSupportFragmentManager(),"tag_picker");
}
});
return view;
}
private PendingIntent getAlarmInfoPendingIntent() {
Intent alarmInfoIntent = new Intent(getActivity(), StartActivity.class);
alarmInfoIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
return PendingIntent.getActivity(getActivity(),0,alarmInfoIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
private PendingIntent getAlarmActionPendingIntent() {
Intent intent = new Intent(getActivity(), AlarmActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
return PendingIntent.getActivity(getActivity(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.vitaliy.numbell">
<uses-permission android:name="android.permission.INTERNET" />
<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/Theme.Numbell">
<activity android:name=".AlarmActivity" />
<receiver
android:name=".Widget"
android:exported="true">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/widget_info" />
</receiver>
<activity
android:name=".AppActivity"
android:configChanges="colorMode|keyboardHidden|screenSize|orientation|locale"
android:exported="false"
android:screenOrientation="portrait" />
<activity
android:name=".StartActivity"
android:configChanges="colorMode|keyboardHidden|screenSize|orientation|locale"
android:exported="true"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
AlarmActivity (Activity that opens when the alarm goes off):
package org.vitaliy.numbell;
public class AlarmActivity extends AppCompatActivity {
Ringtone ringtone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
WindowCompat.setDecorFitsSystemWindows(getWindow(), false);
Uri notificationUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
ringtone = RingtoneManager.getRingtone(this, notificationUri);
if(ringtone==null){
notificationUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
ringtone = RingtoneManager.getRingtone(this, notificationUri);
}
if(ringtone != null){
ringtone.play();
}
}
#Override
protected void onDestroy() {
if(ringtone != null && ringtone.isPlaying()){
ringtone.stop();
}
super.onDestroy();
}
}
A better approach to this can be to show alarm via notifications (Broadcast Receiver) when app is not in background and when phone is locked or on standby you can call an activity there.
First off all add these two lines to Manifest to show activities on lockscreen:
<activity
android:name=".AppActivity"
android:configChanges="colorMode|keyboardHidden|screenSize|orientation|locale"
android:exported="false"
android:screenOrientation="portrait"
android:showOnLockScreen="true"
android:showWhenLocked="true" />
After this you can use KeyGuardManager and PowerManager to check in which state your phone is:
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if (pm.isInteractive() && pm.isScreenOn() && keyguardManager.isKeyguardLocked() && keyguardManager.isDeviceLocked()) {
// This will be helpful to show your activity or notification on lock screen
}
I am trying to make an android application where I receive notification using firebase. I followed resources available over the internet.
All I want to do is send notification from firebase, the message that I receive I want to display it in TextView in main activity.
Currently I am testing in an emulator. There are few problems that I am not able to resolve.
I am able to send notification from firebase but:
When the application is running in foreground I don't receive a notification in the android notification panel and nothing happens in the main activity too. That is the text in TextView does not change.
When the application is running in background I do receive the notification in android notification panel with message sent from firebase, clicking the notification main activity opens but the text in TextView does not change.
Firebase Messaging Service
public class VAFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "VAFirebaseMessagingS";
public VAFirebaseMessagingService() {}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d(TAG, "From: " + remoteMessage.getFrom());
if(remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
sendNotification(remoteMessage.getData().get("text"));
}
if(remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody());
}
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(Intent.EXTRA_TEXT, messageBody);
PendingIntent pendingIntent = PendingIntent
.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setSmallIcon(R.drawable.ic_stat_name);
notificationBuilder.setContentTitle("PFIVA");
notificationBuilder.setContentText(messageBody);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSound(defaultSoundUri);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
Main Activity
public class MainActivity extends AppCompatActivity {
private TextView userFeedbackQuery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userFeedbackQuery = (TextView) findViewById(R.id.pfiva_user_feedback_query);
final Intent intent = getIntent();
if(intent.hasExtra(Intent.EXTRA_TEXT)) {
String userFeedbackQueryText = intent.getStringExtra(Intent.EXTRA_TEXT);
userFeedbackQuery.setText(userFeedbackQueryText);
}
}
}
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.pfiva.mobile.voiceassistant">
<uses-permission android:name="android.permission.INTERNET" />
<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=".activities.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".messaging.FirebaseInstanceService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service
android:name=".messaging.VAFirebaseMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
</manifest>
Please can someone guide what is wrong here? How can i solve the above two problems.
Thanks
After suggestions i made the below changes in Messaging Service, basically added notification channel.
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(Intent.EXTRA_TEXT, messageBody);
PendingIntent pendingIntent = PendingIntent
.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID);
notificationBuilder.setSmallIcon(R.drawable.ic_stat_name);
notificationBuilder.setContentTitle("PFIVA");
notificationBuilder.setContentText(messageBody);
notificationBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSound(defaultSoundUri);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0, notificationBuilder.build());
}
Problem i face now is that when the app is running in background, i do receive notification in notification panel and clicking on it open main activity but the text in TextView is not updated.
Two ideas to solve your issue:
Have you register your VAFirebaseMessagingService in your AndroidManifest.xml:
Since Android 8, you must use an Notification Channel to send push notifications. Android
I create an android application to view notification at a particular time when the application is not running background . I use AlarmMabager & BroadcastReceiver for above purpose .
This application can pass a notification at a specific time whether user is not starting the application .
Here are the steps which I use to do ,
MainActivity.java
public class MainActivity extends Activity
{
private PendingIntent pendingIntent;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, 7);
calendar.set(Calendar.YEAR, 2016);
calendar.set(Calendar.DAY_OF_MONTH, 7);
calendar.set(Calendar.HOUR_OF_DAY, 13);
calendar.set(Calendar.MINUTE, 40);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM,Calendar.PM);
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
} //end onCreate
}
MyReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);
}
}
MyAlarmService.java
public class MyAlarmService extends Service
{
private NotificationManager mManager;
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
Notification notification = new Notification(R.mipmap.ic_launcher,"This is a test message!", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);
mManager.notify(0, notification);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="10" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.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=".MyAlarmService"
android:enabled="true" />
<receiver android:name=".MyReceiver"/>
</application>
</manifest>
After completing all the steps I run the application in my device but it doesn't show any notification . Is there anything wrong ? What should I do to correct this .
Thank you .
I would like to start new activity after few seconds with BroadcastReceiver. New Activity needs to be started even if the app is closed in the meantime.
For now I have this but nothing happens when I run it:
Main.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), Receiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1, intent, 0);
int seconds = 5;
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, seconds);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);;
}
});
}
Receiver.java
public class Receiver extends BroadcastReceiver {
private PowerManager.WakeLock mWakelock;
#SuppressWarnings("deprecation")
private KeyguardManager.KeyguardLock mLock;
private static ContentResolver sResolver;
#SuppressWarnings("deprecation")
#Override
public void onReceive(Context paramContext, Intent intent) {
this.mWakelock = ((PowerManager) paramContext.getSystemService("power"))
.newWakeLock(805306394/* | PowerManager.ON_AFTER_RELEASE */,
"wakelock");
this.mWakelock.acquire();
this.mLock = ((KeyguardManager) paramContext
.getSystemService("keyguard")).newKeyguardLock("");
this.mLock.disableKeyguard();
setLockPatternEnabled(true);
sResolver = paramContext.getContentResolver();
Intent startMain;
startMain = new Intent(paramContext, NewActivity.class);
startMain.setAction("com.name.NewActivity");
startMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paramContext.startActivity(startMain);
}
/**
* used for to enable lock in all patterns
*
* #param enabled
*/
#SuppressWarnings("deprecation")
public static void setLockPatternEnabled(boolean enabled) {
setBoolean(android.provider.Settings.System.LOCK_PATTERN_ENABLED,
enabled);
}
private static void setBoolean(String systemSettingKey, boolean enabled) {
android.provider.Settings.System.putInt(sResolver, systemSettingKey,
enabled ? 1 : 0);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.name" >
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.Light.NoTitleBar" >
<activity
android:name=".Main"
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="com.name.NewActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.name.NewActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
Does anyone know where is the problem? I also need that this new Activity unlocks the screen if it's locked, like alarm or call does.
You can do something like this: (ignore this one)
int millis = 500;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(SplashScreenActivity.this, HomeActivity.class));
SplashScreenActivity.this.finish();
}
}, millis);
Update 1 (should work): Try this in your MainActivity, your probably counting time in wrong way so use calendar. If it works, I'll try to explain.
Intent intent = new Intent(this, Receiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0); //Or you can get broadcast in your way.
int seconds = 25;
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, seconds);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Update 2: You should register your receiver in the manifest. In some cases there are intent filters on receivers but I it should work like that. Be sure that name of your package and receiver are correct.
<application ...>
<activity ...>
...
<receiver android:name=".package.YourReceiver">
</receiver>
...
</application>
I have a receiver that works well, but I can't seem to show a proper UI, although the toast appears correctly. As far as I can tell, this is caused by Android requiring the class to extend Activity, however, the class already extends BroadcastReceiver, so I can't do this.
So, I tried to do an Intent, but this failed too. There are no errors, but the screen doesn't show. Source code is below.
Broadcast (Method in AndyRoidAlarm)
public void setAlarm(){
Intent intent = new Intent(AndyRoidAlarm.this, Reciever.class);
PendingIntent sender = PendingIntent.getBroadcast(AndyRoidAlarm.this,
0, intent, 0);
// We want the alarm to go off 30 seconds from now.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
// Schedule the alarm!
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
// Tell the user about what we did.
if (mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(AndyRoidAlarm.this, "Alarm Scheduled for 30secs", Toast.LENGTH_LONG);
mToast.show();
}
Reciever
public class Reciever extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Alarm Received", Toast.LENGTH_LONG).show();
Intent i = new Intent();
i.setClass(context, AlarmRing.class);
}
}
Reciever V2
#Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Alarm Received", Toast.LENGTH_LONG).show();
Intent foo = new Intent(context, AlarmRing.class);
//foo.putExtra("id", "id");//example, if you wish to pass custom variables
context.startActivity(foo);
}
AlarmRing
public class AlarmRing extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alarm);
MediaPlayer mp = MediaPlayer.create(getBaseContext(), R.raw.sweetchild);
mp.start();
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.comaad.andyroidalarm"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".AndyRoidAlarm"
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.comaad.andyroidalarm.Reciever" android:enabled="true">
<intent-filter>
<action android:name="com.comaad.andyroidalarm.Reciever"></action>
</intent-filter>
</receiver>
<activity android:name=".AlarmRing"></activity>
</application>
</manifest>
}
In a BroadcastReceiver onReceive() method, if you need a Context (e.g., to create an Intent), use the Context that is passed to you as a parameter of onReceive(). You even have this code in your onReceive() -- you're just not doing anything with the resulting Intent (e.g., calling startActivity()).
Intent foo = new Intent(this, AlarmRing.class);
foo.putExtra("id", id);//example, if you wish to pass custom variables
this.startActivity(foo);
Edit
Check out this example to use BroadcastReciever within an Activity. http://almondmendoza.com/2009/01/04/getting-battery-information-on-android/