I am making a simple reminder app. I am getting a null pointer exception when the reminder goes off.
Here the key info from Logcat: Caused by: java.lang.NullPointerException
at com.joshbgold.move.AlarmReceiver.onReceive(AlarmReceiver.java:34)
Evidently I am not initializing AlarmActivity inst properly. I know this is probably a simple fix, thanks for your patience with a newer Java programmer.
AlarmReceiver.java:
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v4.content.WakefulBroadcastReceiver;
/**
* Created by JoshG on 7/6/2015.
*/
public class AlarmReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
//MediaPlayer is used to play an mp3 file
final MediaPlayer mediaPlayer = MediaPlayer.create(context, R.drawable.om_mani_short);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaplayer) {
mediaplayer.stop();
mediaplayer.release();
}
});
mediaPlayer.start();
//this will update the UI with message
AlarmActivity inst = AlarmActivity.instance();
inst.setAlarmText("stretch");
//this will send a notification message
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
AlarmActivity.java:
package com.joshbgold.move;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.ToggleButton;
import java.util.Calendar;
/**
* Created by JoshG on 7/6/2015.
*/
public class AlarmActivity extends Activity {
AlarmManager alarmManager;
private PendingIntent pendingIntent;
private TimePicker alarmTimePicker;
private static AlarmActivity inst;
private TextView alarmTextView;
public static AlarmActivity instance() {
return inst;
}
#Override
public void onStart() {
super.onStart();
inst = this;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmTimePicker = (TimePicker) findViewById(R.id.alarmTimePicker);
alarmTextView = (TextView) findViewById(R.id.alarmText);
ToggleButton alarmToggle = (ToggleButton) findViewById(R.id.alarmToggle);
final Button exitButton = (Button) findViewById(R.id.exitButton);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
final MediaPlayer mediaPlayer = MediaPlayer.create(this, R.drawable.om_mani_short);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaplayer) {
mediaplayer.stop();
mediaplayer.release();
}
});
mediaPlayer.start();
View.OnClickListener quitApp = new View.OnClickListener() { //this block stops music when exiting
#Override
public void onClick(View view) {
if (mediaPlayer != null) try {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
} catch (Exception e) {
Log.d("Alarm Activity", e.toString());
}
finish();
}
};
exitButton.setOnClickListener(quitApp);
}
public void onToggleClicked(View view) {
if (((ToggleButton) view).isChecked()) {
Log.d("MyActivity", "Alarm On");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
Intent myIntent = new Intent(AlarmActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(AlarmActivity.this, 0, myIntent, 0);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
} else {
alarmManager.cancel(pendingIntent);
setAlarmText("Alarm Off");
Log.d("MyActivity", "Alarm Off");
}
}
public void setAlarmText(String alarmText) {
alarmTextView.setText(alarmText);
}
}
Alarm Service.java
package com.joshbgold.move;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
/**
* Created by JoshG on 7/6/2015.
*/
public class AlarmService extends IntentService {
private NotificationManager alarmNotificationManager;
public AlarmService() {
super("AlarmService");
}
#Override
public void onHandleIntent(Intent intent) {
sendNotification("stretch");
}
private void sendNotification(String msg) {
Log.d("AlarmService", "Preparing to send notification...: " + msg);
alarmNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, AlarmActivity.class), 0);
NotificationCompat.Builder alarmNotificationBuilder = new NotificationCompat.Builder(
this).setContentTitle("Reminder").setSmallIcon(R.mipmap.ic_launcher)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
alarmNotificationBuilder.setContentIntent(contentIntent);
alarmNotificationManager.notify(1, alarmNotificationBuilder.build());
Log.d("AlarmService", "Notification sent.");
}
}
Here is the contents of Logcat. I have it set to Log Level of Error:
07-07 18:53:13.119 13065-13065/com.joshbgold.move E/﹕ mali: REVISION=Linux-r3p2-01rel2 BUILD_DATE=Mon Nov 18 21:41:36 KST 2013
07-07 19:00:11.569 16746-16746/com.joshbgold.move E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start receiver com.joshbgold.move.AlarmReceiver: java.lang.NullPointerException
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2469)
at android.app.ActivityThread.access$1600(ActivityThread.java:158)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1372)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5365)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.joshbgold.move.AlarmReceiver.onReceive(AlarmReceiver.java:34)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2462)
at android.app.ActivityThread.access$1600(ActivityThread.java:158)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1372)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5365)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
If this is the class, line 34 is
inst.setAlarmText("stretch");
which points to the line above it not getting an actual activity
AlarmActivity inst = AlarmActivity.instance();
Check your AlarmActivity class to make sure inst is not null when it is created with the instance() method.
Can you post your AlarmActivity class to see how you are creating/fetching your instance?
//this will update the UI with message
AlarmActivity inst = AlarmActivity.instance();
inst.setAlarmText("stretch");
inst is null. You should check AlarmActivity.instance()
public static AlarmActivity instance() {
if (inst == null) {
// Do something such as inst = ...
}
return inst;
}
I took a sharp right turn, and did a different implementation when the reminder/alarm goes off. While I am doing something a little different then originally intended, the above answers provided led me in the correct direction.
Here is what I am using for AlarmReceiver.java:
package com.joshbgold.move;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
public class AlarmReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
//this will change to new activity for Reminder(s) at the appropriate time
Intent myIntent = new Intent();
myIntent.setClassName("com.joshbgold.move", "com.joshbgold.move.ReminderActivity");
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
}
}
Related
I faced error
developer warning for package "package name" fail to post
notification on channel "null" more see in Logcat
can anyone help me with a normal app that uses TimePicker to set the time ..and also uses intents,etc instead of normal comparisons.This is the code that i've done till now.But this is not working. The 'TimePicker' sets the time and on pressing the 'ToggleButton' a 'TextVew' shows that alarm is on .But when the alarmtime is reached,Alarm Ringing message is not shown.Please someone help me out. this is the code of main activity
AlarmNotificationReceiver
package com.example.kishorsinh.yogaapp;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
public class AlarmNotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Intent in = new Intent(context, ListExercises.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context,
0, in, 0);
builder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.yoga)
.setContentTitle("It's About Time")
.setContentText("text.... ")
.setContentInfo("text....")
.setContentIntent(pendingIntent)
.setPriority(Notification.PRIORITY_HIGH);
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,builder.build());
}
}
Setting Page
package com.example.kishorsinh.yogaapp;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.example.kishorsinh.yogaapp.Database.YogaDB;
import java.util.Calendar;
import java.util.Date;
public class SettingPage extends AppCompatActivity {
Button btnSave;
RadioButton rdiEasy,rdiMedium,rdiHard;
RadioGroup rdiGroup;
YogaDB yogaDB;
ToggleButton switchAlarm;
TimePicker timePicker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setting_page);
//init view
btnSave = (Button) findViewById(R.id.btnSave);
rdiGroup = (RadioGroup) findViewById(R.id.rdiogroup);
rdiEasy = (RadioButton) findViewById(R.id.rdioEasy);
rdiMedium = (RadioButton) findViewById(R.id.rdioMedium);
rdiHard = (RadioButton) findViewById(R.id.rdioHard);
switchAlarm = (ToggleButton) findViewById(R.id.switchAlarm);
timePicker = (TimePicker) findViewById(R.id.timePicker);
yogaDB = new YogaDB(this);
int mode = yogaDB.getSettingMode();
setRadioButton(mode);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveWorkoutMode();
saveAlarm(switchAlarm.isChecked());
Toast.makeText(SettingPage.this, "Saved!!", Toast.LENGTH_SHORT).show();
finish();
}
});
}
private void saveAlarm(boolean checked) {
if(checked)
{
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent;
PendingIntent pendingIntent;
intent = new Intent(SettingPage.this,AlarmNotificationReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this,0,intent,0);
//Set time for alarm
Calendar calendar = Calendar.getInstance();
Date toDay = Calendar.getInstance().getTime();
if (Build.VERSION.SDK_INT >= 23 ) {
//new version mate
calendar.set(toDay.getYear(), toDay.getMonth(), toDay.getDate(), timePicker.getHour(), timePicker.getMinute());
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
Log.d("DEBUG", "Alarm will wake at" + timePicker.getHour() + ":" + timePicker.getMinute());
}
else
{
//olderversion mate
calendar.set(toDay.getYear(), toDay.getMonth(), toDay.getDate(), timePicker.getCurrentHour(), timePicker.getCurrentMinute());
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
Log.d("DEBUG", "Alarm will wake at" + timePicker.getCurrentHour() + ":" + timePicker.getCurrentMinute());
}
}
else
{
//Cancel Alarm
Intent intent = new Intent(SettingPage.this,AlarmNotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
}
private void saveWorkoutMode() {
int selectedID = rdiGroup.getCheckedRadioButtonId();
if(selectedID == rdiEasy.getId())
{
//Toast.makeText(this, "Your Workout Mode time: 30sec", Toast.LENGTH_LONG).show();
yogaDB.saveSettingMode(0);
}
else if(selectedID == rdiMedium.getId())
{
//Toast.makeText(this, "Your Workout Mode time: 20sec", Toast.LENGTH_LONG).show();
yogaDB.saveSettingMode(1);
}
if(selectedID == rdiHard.getId())
{
//Toast.makeText(this, "Your Workout Mode time: 10sec", Toast.LENGTH_LONG).show();
yogaDB.saveSettingMode(2);
}
}
private void setRadioButton(int mode) {
if(mode == 0)
rdiGroup.check(R.id.rdioEasy);
else if(mode == 1)
rdiGroup.check(R.id.rdioMedium);
else if(mode == 2)
rdiGroup.check(R.id.rdioHard);
}
}
.
.
..
.
.
.
.
...........................................................................................................
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
My application stopped when I finished working on the quiz application. I'm learning to make an Android application quiz using MySQL database, but I get the problem when the last question will move to the scoring page.
10-28 01:02:25.816 31874-31874/com.example.nuvo.myapplication
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.nuvo.myapplication, PID: 31874
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.nuvo.myapplication/com.example.nuvo.myapplication.Complete}:
java.lang.NullPointerException
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2429)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
at android.app.ActivityThread.access$800(ActivityThread.java:166)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at
com.example.nuvo.myapplication.Complete.onCreate(Complete.java:18)
at android.app.Activity.performCreate(Activity.java:5442)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2393)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2493)
at android.app.ActivityThread.access$800(ActivityThread.java:166)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1283)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
Complate.java
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class Complete extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complete);
int score = getIntent().getExtras().getInt("score");
AlertDialog.Builder builder = new AlertDialog.Builder(Complete.this);
builder.setTitle("Quiz Complete");
builder.setMessage("Your Score is: " +score+ " out of 10");
builder.show();
builder.setPositiveButton("Play Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
Intent intent = new Intent(Complete.this, QuizActivity.class);
startActivity(intent);
}
});
builder.setNegativeButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void restartQuiz(View view)
{
Intent intent = new Intent(Complete.this, QuizActivity.class);
startActivity(intent);
}
public void mainMenu(View view)
{
Intent intent = new Intent(Complete.this, MainActivity.class);
startActivity(intent);
}
}
QuizActivity.java
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class Complete extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complete);
int score = getIntent().getExtras().getInt("score");
AlertDialog.Builder builder = new AlertDialog.Builder(Complete.this);
builder.setTitle("Quiz Complete");
builder.setMessage("Your Score is: " +score+ " out of 10");
builder.show();
builder.setPositiveButton("Play Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
Intent intent = new Intent(Complete.this, QuizActivity.class);
startActivity(intent);
}
});
builder.setNegativeButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void restartQuiz(View view)
{
Intent intent = new Intent(Complete.this, QuizActivity.class);
startActivity(intent);
}
public void mainMenu(View view)
{
Intent intent = new Intent(Complete.this, MainActivity.class);
startActivity(intent);
}
}
This line is problematic in your code:
int score = getIntent().getExtras().getInt("score");
It seems that your Intent, which opened your Complete activity did not have an integer "score" and hence returned null, which caused NullPointerException. To avoid such problems consider using another method getInt(String key, int defaultValue) s.a. this:
int score = getIntent().getExtras().getInt("score", 0);
This way you'll not get an exception if your Intent arrives without a value, but it will be set to 0 by default.
I am new to android development and have very little knowledge in java and I have seen this Alarm Clock app tutorial in the internet. The application has problems. It can't set time before the current time of phone and it doesn't start at the exact time. How to make this application so it can set alarm within 24 hours and at the exact time?
AlarmActivity.java
package com.javapapers.androidalarmclock;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.ToggleButton;
import java.util.Calendar;
public class AlarmActivity extends Activity {
AlarmManager alarmManager;
private PendingIntent pendingIntent;
private TimePicker alarmTimePicker;
private static AlarmActivity inst;
private TextView alarmTextView;
public static AlarmActivity instance() {
return inst;
}
#Override
public void onStart() {
super.onStart();
inst = this;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
alarmTimePicker = (TimePicker) findViewById(R.id.alarmTimePicker);
alarmTextView = (TextView) findViewById(R.id.alarmText);
ToggleButton alarmToggle = (ToggleButton) findViewById(R.id.alarmToggle);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
}
public void onToggleClicked(View view) {
if (((ToggleButton) view).isChecked()) {
Log.d("MyActivity", "Alarm On");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
Intent myIntent = new Intent(AlarmActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(AlarmActivity.this, 0, myIntent, 0);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
} else {
alarmManager.cancel(pendingIntent);
setAlarmText("");
Log.d("MyActivity", "Alarm Off");
}
}
public void setAlarmText(String alarmText) {
alarmTextView.setText(alarmText);
}
}
AlarmReceiver.java
package com.javapapers.androidalarmclock;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.content.WakefulBroadcastReceiver;
public class AlarmReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
//this will update the UI with message
AlarmActivity inst = AlarmActivity.instance();
inst.setAlarmText("Alarm! Wake up! Wake up!");
//this will sound the alarm tone
//this will sound the alarm once, if you wish to
//raise alarm in loop continuously then use MediaPlayer and setLooping(true)
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
//this will send a notification message
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
AlarmService.java
package com.javapapers.androidalarmclock;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class AlarmService extends IntentService {
private NotificationManager alarmNotificationManager;
public AlarmService() {
super("AlarmService");
}
#Override
public void onHandleIntent(Intent intent) {
sendNotification("Wake Up! Wake Up!");
}
private void sendNotification(String msg) {
Log.d("AlarmService", "Preparing to send notification...: " + msg);
alarmNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, AlarmActivity.class), 0);
NotificationCompat.Builder alamNotificationBuilder = new NotificationCompat.Builder(
this).setContentTitle("Alarm").setSmallIcon(R.drawable.ic_launcher)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
alamNotificationBuilder.setContentIntent(contentIntent);
alarmNotificationManager.notify(1, alamNotificationBuilder.build());
Log.d("AlarmService", "Notification sent.");
}
}
Please Help! I am desperate.
If you want to have a 24hour span, you also need to set the day, that's why you can't set the time before the current time of the phone.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute());
if(calendar.getTimeInMillis() < System.currentTimeMillis())
calendar.add(Calendar.DAY, 1);
https://stackoverflow.com/a/20438452/6873402
I would just like to share this answer that I found about the Delay Problem in the Alarm Clock
i am new to android development and i am writing an app for my college project .The app transmits a string of data stored in shared preferences .The data is stored by one time setup screen which is never shown again.The issue is after first time,when app is started again it shows that "app has unfortunately stopped working "and when i click ok the app starts.Can anybody tell me why this is happening?
Code:
package com.example.homeautomation.zigbeehomeauto;
import android.annotation.TargetApi;
import android.content.SharedPreferences;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Toast;
public class MainScreen extends ActionBarActivity {
NdefMessage msg;
NfcAdapter nfcadapter;
public static final String PREFS_NAME = "MyPrefsFile";
public String pass2 ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
SharedPreferences check = getSharedPreferences(PREFS_NAME, 0);
String Pass = check.getString("Str", "Nothing");
pass2 = Pass;
nfcadapter = NfcAdapter.getDefaultAdapter(this);
if (nfcadapter == null) {
Toast.makeText(this, "NFC is not available User", Toast.LENGTH_LONG)
.show();
finish();
}
}
public void ExApp(View v) {
finish();
System.exit(0);
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void Nsend(View v)
{
byte[] stringBytes = pass2.getBytes();
nfcadapter.setNdefPushMessage(msg = new NdefMessage(new NdefRecord[]{NdefRecord.createMime("text/plain", stringBytes)
}),this);
}
}
Logcat Ouput:
04-07 12:04:38.478 10836-10836/com.example.homeautomation.zigbeehomeauto E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.homeautomation.zigbeehomeauto, PID: 10836
android.util.SuperNotCalledException: Activity {com.example.homeautomation.zigbeehomeauto/com.example.homeautomation.zigbeehomeauto.SetupScreen} did not call through to super.onCreate()
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2510)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2603)
at android.app.ActivityThread.access$900(ActivityThread.java:174)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5752)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Check in your SetupScreen.java do you have super.onCreate(savedInstanceState);
after onCreate() Method is starts .
post your SetupScreen.java code also ..
Your onCreate() method of class SetupScreen do not call the super.onCreate(). Add the statement and the error should go away.
I have an Alarmmanager that is repeatedly calling an AlarmReceiver. The AlarmReceiver in turn calls an activity (com.example.testapp.Activity). My problem is that after few calls the UI of my main activity is displayed again, which should not be the case. What can be done to prevent the UI from popping up?
I already tried to set (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_NO_ANIMATION) in the AlarmReceiver. My main activity has android:theme="#android:style/Theme.NoDisplay in the manifest.
I only want the UI of the main activity to be displayed when the user clicks the icon for starting the app. (Then the user clicks the start button of the main activity and from there on everything should run without UI).
Here is the AlarmReceiver code:
package com.example.testapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
try {
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
//start activity
Intent i = new Intent();
i.setClassName("com.example.testapp", "com.example.testapp.Activity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here is the activity code:
package com.example.testapp;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.database.Cursor;
import android.provider.Browser;
import android.content.Intent;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Activity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// a lot of code
Here is the main activity:
package com.example.testapp;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
findViewById(R.id.startAlarm).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Alarm begin", Toast.LENGTH_SHORT).show();
// instantiate AlarmService.java
Intent intent = new Intent(MyActivity.this, AlarmService.class);
// start service
startService(intent);
}
});
findViewById(R.id.stopAlarm).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PendingIntent pendingIntent;
/* Retrieve a PendingIntent that will perform a broadcast */
Intent alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent);
Toast.makeText(MainActivity.this, "Alarm Canceled", Toast.LENGTH_SHORT).show();
}
});
}
}
Here is the code of the AlarmManager:
new Thread(new Runnable() {
#Override
public void run() {
{
PendingIntent pendingIntent;
/* Retrieve a PendingIntent that will perform a broadcast */
Intent alarmIntent = new Intent(AlarmService.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(AlarmService.this, 0, alarmIntent, 0);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int interval = 10000;
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
} catch (Exception e) {
e.printStackTrace();
}