web-dev-qa-db-ja.com

Androidでアラームを設定する方法は?

以下は私のコードの缶ですどんなボディでもそれがうまくいかない理由を教えてください。私はそれを このチュートリアル から学びました。しかし、それが機能していない場合は、かなりの助けになります。

私のコードは

import Java.util.Calendar;

import Android.app.Activity;
import Android.app.AlarmManager;
import Android.app.ListActivity;
import Android.app.Notification;
import Android.app.NotificationManager;
import Android.app.PendingIntent;
import Android.content.Context;
import Android.content.Intent;
import Android.os.Bundle;
import Android.widget.ArrayAdapter;
import Android.widget.Button;
import Android.widget.ListView;
import Android.widget.AdapterView.OnItemClickListener;
import Android.widget.Toast;


public class Notify extends Activity {
    Button btn;

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.nit);
        Calendar cal=Calendar.getInstance();
        cal.set(Calendar.MONTH,6);
        cal.set(Calendar.YEAR,2011);
        cal.set(Calendar.DAY_OF_MONTH,29);
        cal.set(Calendar.HOUR_OF_DAY,17);
        cal.set(Calendar.MINUTE,30);

        //String[] dude=new String[] {"nitin","avi","aman","rahul","pattrick","minkle","manmohan","nitin","nitin"};

        //setListAdapter(new ArrayAdapter<String>(this, Android.R.layout.simple_expandable_list_item_1,dude));
        //getListView().setTextFilterEnabled(true);

        //String[] dude1=new String[] {"nitin","avi","aman","rahul","pattrick","minkle","manmohan"};

        Intent intent = new Intent(this, Mote.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 1253, intent, PendingIntent.FLAG_UPDATE_CURRENT|  Intent.FILL_IN_DATA);

        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

        alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),pendingIntent );
        Toast.makeText(this, "Alarm worked.", Toast.LENGTH_LONG).show();
    }

}

そして私のレシーバークラスは

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.widget.Toast;

public class Mote extends BroadcastReceiver{

    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
        int icon = R.drawable.icon;
        CharSequence tickerText = "Hello you have to take medicine I am Nitin Sharma";
        long when = System.currentTimeMillis();

        //Notification notification = new Notification(icon, tickerText,when );

        CharSequence contentTitle = "My notification";
        CharSequence contentText = "Hello World!";


        //notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
        final int NOTIF_ID = 1234;
        NotificationManager notofManager = (NotificationManager)context. getSystemService(Context.NOTIFICATION_SERVICE);
        // Notification note = new Notification(R.drawable.face,"NEW ACTIVITY", System.currentTimeMillis());
        Intent notificationIntent = new Intent(context, Alset.class);
        PendingIntent contentIntent = PendingIntent.getActivity(context,0, notificationIntent, 0);
        Notification notification = new Notification(icon, tickerText,when );
        //Notification notification1 = new Notification(R.drawable.icon, "Wake up alarm", System.currentTimeMillis());
        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
        notification.flags = Notification.FLAG_INSISTENT;
        notification.defaults |= Notification.DEFAULT_SOUND;
        //notification.setLatestEventInfo(context, "My Activity", "This will runs on button click", contentIntent);
        notofManager.notify(NOTIF_ID,notification);

        //PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
        //notification.setLatestEventInfo(context, "Context Title", "Context text", contentIntent);
        //notification.flags = Notification.FLAG_INSISTENT;
    }



}
14
Nitin

アラームを7月26日ではなく6月26日に設定したいと思います。その場合、月はゼロベースであるため、cal.set(Calendar.MONTH,6);cal.set(Calendar.MONTH,5);に変更します。 7月26日にアラームを起動する場合は、日付時刻が2011年7月26日17:30になるとアラームが起動すると予想されます。

23
pankajagarwal

1.これをマニフェストファイルに追加する

 <receiver Android:name=".MyAlarmReciever">
            <intent-filter>
                <action Android:name="com.example.helloandroid.alarms" />
            </intent-filter>
        </receiver>        
  1. 活動する

         public class AlrmActivity extends BaseAcitivity {
    
            TimePicker myTimePicker;
            Button buttonstartSetDialog;
            TextView textAlarmPrompt;
    
            TimePickerDialog timePickerDialog;
    
            final static int RQS_1 = 1;
    
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_alrm);
    
                textAlarmPrompt = (TextView)findViewById(R.id.alarmprompt);
    
                buttonstartSetDialog = (Button)findViewById(R.id.startSetDialog);
                buttonstartSetDialog.setOnClickListener(new View.OnClickListener(){
    
                    @Override
                    public void onClick(View v) {
                        textAlarmPrompt.setText("");
                        openTimePickerDialog(false);
    
                    }});
    
    
            }
    
            private void openTimePickerDialog(boolean is24r){
                Calendar calendar = Calendar.getInstance();
    
                timePickerDialog = new TimePickerDialog(
                        AlrmActivity.this,
                        onTimeSetListener,
                        calendar.get(Calendar.HOUR_OF_DAY),
                        calendar.get(Calendar.MINUTE),
                        is24r);
                timePickerDialog.setTitle("Set Alarm Time");
    
                timePickerDialog.show();
    
            }
            TimePickerDialog.OnTimeSetListener onTimeSetListener
                    = new TimePickerDialog.OnTimeSetListener(){
    
                @Override
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    
                    Calendar calNow = Calendar.getInstance();
                    Calendar calSet = (Calendar) calNow.clone();
    
                    calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
                    calSet.set(Calendar.MINUTE, minute);
                    calSet.set(Calendar.SECOND, 0);
                    calSet.set(Calendar.MILLISECOND, 0);
    
                    if(calSet.compareTo(calNow) <= 0){
                        //Today Set time passed, count to tomorrow
                        calSet.add(Calendar.DATE, 1);
                    }
    
                    setAlarm(calSet);
                }};
    
            private void setAlarm(Calendar targetCal){
    
                textAlarmPrompt.setText(
                        "\n\n***\n"
                                + "Alarm is set@ " + targetCal.getTime() + "\n"
                                + "***\n");
    
                Intent intent = new Intent(getBaseContext(), MyAlarmReciever.class);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
                AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
                alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
    
            }
    
        }
    

3。 XMLファイルインクルード

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
        Android:layout_width="fill_parent"
        Android:layout_height="fill_parent"
        Android:orientation="vertical" >

        <TextView
            Android:layout_width="fill_parent"
            Android:layout_height="wrap_content"
            Android:text="hello" />
        <Button
            Android:id="@+id/startSetDialog"
            Android:layout_width="fill_parent"
            Android:layout_height="wrap_content"
            Android:text="Set Target Time"/>
        <TextView
            Android:id="@+id/alarmprompt"
            Android:layout_width="fill_parent"
            Android:layout_height="wrap_content" />
    </LinearLayout>

4 .makeアラームマネージャクラス

    public class MyAlarmReciever extends BroadcastReceiver {

        Vibrator v;
        Context ct;
        String  title;


        @Override
        public void onReceive(Context context, Intent intent) {

            // TODO Auto-generated method stub
            ct=context;

            Log.e("onReceive", "ladskjflsakjdflskjdflskjdfslkjdflasdf");
            Toast.makeText(context, "OnReceive alarm test", Toast.LENGTH_SHORT).show();

            v=(Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
            v.vibrate(3000);

            int badgeCount = 1;
           // ShortcutBadger.applyCount(context, badgeCount);

            ShortcutBadger.removeCount(context);

            Bundle bundle = intent.getExtras();
            try{
                  title = intent.getExtras().get("title").toString();
                 // title = intent.getStringExtra("title");
                Toast.makeText(context, title, Toast.LENGTH_LONG).show();
            }catch(Exception e){
                e.printStackTrace();
            }


    //        if (!Utlis.checkNetworkConnection(context)) {
    //
    //            Notification(context, "Wifi Connection off");
    //
    //        } else {
                Notification(context, "Please  pray for this prayer ");

    //        }

        }


        public void Notification(Context context, String message) {
            // Set Notification Title
            String strtitle = "iPray  Prayer Reminder";
            // Open NotificationView Class on Notification Click
            Intent intent = new Intent(context, PrayerForOtherActivity.class);
            // Send data to NotificationView Class
            intent.putExtra("title", title);
            intent.putExtra("text", title);
            // Open NotificationView.Java Activity
            PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);

    //        NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.app_icon, "Previous", pIntent).build();
            // Create Notification using NotificationCompat.Builder
            NotificationCompat.Builder builder = new NotificationCompat.Builder(
                    context)
                    // Set Icon
                    .setSmallIcon(R.drawable.app_icon)
                    // Set Ticker Message
                    .setTicker(message)
                    // Set Title
                    .setContentTitle(context.getString(R.string.app_name))
                    // Set Text
                    .setContentText(message)
                    // Add an Action Button below Notification
                    // Set PendingIntent into Notification
                    .setContentIntent(pIntent)
                    // Dismiss Notification
                    .setAutoCancel(true);

            // Create Notification Manager
            NotificationManager notificationmanager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            // Build Notification with Notification Manager
            notificationmanager.notify(38, builder.build());

        }
    }
4
priti

マニフェストファイルにレシーバーを設定しましたか?このようなもの

<receiver  Android:process=":remote" Android:name=".Mote"></receiver>
2

これが役に立てば幸い

@Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

                Calendar calNow = Calendar.getInstance();
                Calendar calSet = (Calendar) calNow.clone();

                calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
                calSet.set(Calendar.MINUTE, minute);
                calSet.set(Calendar.SECOND, 0);
                calSet.set(Calendar.MILLISECOND, 0);

                if(calSet.compareTo(calNow) <= 0){
                    //Today Set time passed, count to tomorrow
                    calSet.add(Calendar.DATE, 1);
                }

                setAlarm(calSet);
            }};

        private void setAlarm(Calendar targetCal){

            textAlarmPrompt.setText(
                    "\n\n***\n"
                    + "Alarm is set@ " + targetCal.getTime() + "\n"
                    + "***\n");

            Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
            AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    //      alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pendingIntent);
        }
0
yash