Android ::如何重新启动服务并在x时刻运行特定功能

时间:2014-08-07 03:31:30

标签: android service alarmmanager android-pendingintent

问题

我想知道一些概念,如主题所说

应该做什么要求

我认为PendingIntentAlarmManager有助于重启服务

在时间x但我不知道如何让它调用我需要的功能

请建议。

例如

我的服务类中有2个函数,我想注册它

将来在时间x

运行这两个中的一个(取决于用户建议)

我工作的一些代码(编辑)

public class MyActivity extends Activity implements View.OnClickListener {
    private Button b1;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b1 = (Button)findViewById(R.id.cmd1);
        b1.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {


        startIntentAt(5,MyReceiver.class);
        finish();
    }

    private void startIntentAt(int seconds, Class<?> c) {
        Intent myIntent = new Intent(getBaseContext(), c);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(),0, myIntent, 0);

        AlarmManager alarmManager= (AlarmManager)getSystemService(ALARM_SERVICE);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.SECOND, seconds);
        //long interval = 60 * 1000; //
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
    }


public class MyReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent scheduledIntent = new Intent(context, TargetActivity.class);
        scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(scheduledIntent);
    }
}
}

0 个答案:

没有答案