如何在重新启动后创建持久警报

Chi*_*oni 16 android android-alarms android-notifications

目前,我正在开发类似"待办事项列表"的应用程序.我已在我的应用程序中成功实现了NotificationService和SchedularService.此外,我在为任务设置的时间收到警报(通知).以下是我的疑问:

  1. 使用此代码,重启后我的警报会被删除吗?如果是的话,如何克服这一点.
  2. 我保留了任务的优先级功能.但是我想要这样的机制,即如果用户选择优先级"高",那么他应该在30分钟之前,15分钟之前和设定的时间之前接收三次通知.怎么做到这一点?
  3. 我想在引发通知时设置手机的振动功能.怎么做到这一点?
  4. 我想知道,NotifyService.java中已弃用的方法和构造函数可以做些什么.在API级别11中不推荐使用这些:Notification notification = new Notification(icon, text, time);notification.setLatestEventInfo(this, title, text, contentIntent);.在developer.android.com上,他们建议使用Notification.Builder.那么如何使我的应用程序与所有API级别兼容.

这是用于安排警报的代码段:

...
scheduleClient.setAlarmForNotification(c, tmp_task_id);
...
Run Code Online (Sandbox Code Playgroud)

这是ScheduleClient.java类:

public class ScheduleClient {

    private ScheduleService mBoundService;
    private Context mContext;
    private boolean mIsBound;

    public ScheduleClient(Context context)
    {
        mContext = context;
    }

    public void doBindService()
    {   
        mContext.bindService(new Intent(mContext, ScheduleService.class), mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {

            mBoundService = ((ScheduleService.ServiceBinder) service).getService();
        }

        public void onServiceDisconnected(ComponentName className) {

            mBoundService = null;
        }
    };

    public void setAlarmForNotification(Calendar c, int tmp_task_id){

        mBoundService.setAlarm(c, tmp_task_id);
    }

    public void doUnbindService() {
        if (mIsBound)
        {           
            mContext.unbindService(mConnection);
            mIsBound = false;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是ScheduleService.java:

public class ScheduleService extends Service {

    int task_id;

    public class ServiceBinder extends Binder {

        ScheduleService getService() {

            return ScheduleService.this;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {

        return mBinder;
    }

    private final IBinder mBinder = new ServiceBinder();

    public void setAlarm(Calendar c, int tmp_task_id) {

        new AlarmTask(this, c, tmp_task_id).run();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是AlarmTask.java:

public class AlarmTask implements Runnable{

    private final Calendar date;
    private final AlarmManager am;
    private final Context context;
    int task_id;

    public AlarmTask(Context context, Calendar date, int tmp_task_id) {
        this.context = context;
        this.am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        this.date = date;

        task_id = tmp_task_id;
    }

    @Override
    public void run() {

        Intent intent = new Intent(context, NotifyService.class);
        intent.putExtra(NotifyService.INTENT_NOTIFY, true);
        intent.putExtra("task_id", task_id);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);

        am.set(AlarmManager.RTC, date.getTimeInMillis(), pendingIntent);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是NotifyService.java:

public class NotifyService extends Service {

    public class ServiceBinder extends Binder
    {   
        NotifyService getService()
        {
            return NotifyService.this;
        }
    }

    int task_id;
    private static final int NOTIFICATION = 123;
    public static final String INTENT_NOTIFY = "com.todotaskmanager.service.INTENT_NOTIFY";
    private NotificationManager mNM;
    SQLiteDatabase database;

    @Override
    public void onCreate() {

        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        String tmp_task_brief = null;
        task_id = intent.getIntExtra("task_id", 0);

        loadDatabase();
        Cursor cursor = database.query("task_info", new String[]{"task_brief"}, "task_id=?", new String[]{task_id+""}, null, null, null);
        while(cursor.moveToNext())
        {
            tmp_task_brief = cursor.getString(0);
        }
        cursor.close();

        if(intent.getBooleanExtra(INTENT_NOTIFY, false))
            showNotification(tmp_task_brief);

        return START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {

        return mBinder;
    }

    private final IBinder mBinder = new ServiceBinder();

    private void showNotification(String tmp_task_brief) {

        CharSequence title = "To Do Task Notification!!";
        int icon = R.drawable.e7ca62cff1c58b6709941e51825e738f;
        CharSequence text = tmp_task_brief;     
        long time = System.currentTimeMillis();

        Notification notification = new Notification(icon, text, time);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, TaskDetails.class), 0);

        notification.setLatestEventInfo(this, title, text, contentIntent);

        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        mNM.notify(NOTIFICATION, notification);

        stopSelf();
    }

    void loadDatabase()
    {
        database = openOrCreateDatabase("ToDoDatabase.db",
                SQLiteDatabase.OPEN_READWRITE, null);
    }
}
Run Code Online (Sandbox Code Playgroud)

Luc*_*fer 34

使用此代码,重启后我的警报会被删除吗?如果是的话,如何克服这一点.

是警报将被删除,为了解决这个问题,您需要使用Android的Component,名为BroadcastReceiver,如下所示,

首先,您需要清单中的权限:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Run Code Online (Sandbox Code Playgroud)

此外,在清单中,定义服务并侦听启动完成的操作:

<receiver
    android:name=".receiver.StartMyServiceAtBootReceiver"
    android:enabled="true"
    android:exported="true"
    android:label="StartMyServiceAtBootReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)

然后,您需要定义将获得BOOT_COMPLETED操作并启动服务的接收器.

public class StartMyServiceAtBootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
            Intent serviceIntent = new Intent("com.myapp.NotifyService");
            context.startService(serviceIntent);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您的服务应该在手机启动时运行.

2对于振动

您需要再次在AndroidManifest.xml文件中定义权限,如下所示,

<uses-permission android:name="android.permission.VIBRATE"/>
Run Code Online (Sandbox Code Playgroud)

这是振动的代码,

// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// Vibrate for 300 milliseconds
v.vibrate(300);
Run Code Online (Sandbox Code Playgroud)