如何在特定时间开始申请

Swa*_*oid 5 android android-intent

我想将此工具添加到我的应用程序中,用户可以在其中设置应用程序启动时间,然后应用程序启动.如何在用户特定时间使用广播接收器打开我的应用程序.我不确定这在Android中是否可行?如果你有什么想法请分享.这是主要的活动代码

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lv1=(ListView)findViewById(R.id.listView);
    final ImageView splashImage = (ImageView) findViewById(R.id.imageView1);
    splashImage.setBackgroundResource(R.layout.splash);
    AnimationDrawable  splashAnimation = (AnimationDrawable) splashImage.getBackground();
    splashImage.onWindowFocusChanged(true);
    splashAnimation.start();    
    AlarmManager am = (AlarmManager) getBaseContext().getSystemService(Context.ALARM_SERVICE);
    Date futureDate = new Date(new Date().getTime() + 86400000);
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.MINUTE, 1);// start app in 1 min again
    futureDate.setHours(0);
    futureDate.setMinutes(0);
    futureDate.setSeconds(20);
    Intent intent = new Intent(getBaseContext(), MyAppReciever.class);
    PendingIntent sender = PendingIntent.getBroadcast(getBaseContext(), 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    am.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis() , sender);}}
Run Code Online (Sandbox Code Playgroud)

这是reciver类代码

class MyAppReciever extends BroadcastReceiver{ public void onReceive(Context context,Intent intent) {
startActivity(new Intent(context, Main_Activity.class));
}private void startActivity(Intent intent) {
// TODO Auto-generated method stub}}
Run Code Online (Sandbox Code Playgroud)

我已将此行添加到清单中

<receiver  android:process=":remote" android:name="MyAppReciever"></receiver>
Run Code Online (Sandbox Code Playgroud)

现在我的广播触发器,但我得到了这个错误

10-02 17:56:27.735: E/AndroidRuntime(9020): java.lang.RuntimeException: Unable to instantiate receiver com.example.testgui.MyAppReciever: java.lang.IllegalAccessException: access to class not allowed
Run Code Online (Sandbox Code Playgroud)

谢谢

Mil*_*loš 7

正如@Paul D'Ambra所说,你可以用AlarmManager做到这一点.

例:

首先,您需要设置警报:

AlarmManager am = (AlarmManager) con.getSystemService(Context.ALARM_SERVICE);

Date futureDate = new Date(new Date().getTime() + 86400000);


futureDate.setHours(8);
futureDate.setMinutes(0);
futureDate.setSeconds(0);


Intent intent = new Intent(con, MyAppReciever.class);

PendingIntent sender = PendingIntent.getBroadcast(con, 0, intent,
        PendingIntent.FLAG_UPDATE_CURRENT);
Run Code Online (Sandbox Code Playgroud)

下一步您需要创建一个带有一些代码来执行的接收器(即启动您的应用程序):

public class MyAppReciever extends BroadcastReceiver {

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

    startActivity(new Intent(context, MyApp.class));
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 在这段代码中,我只需要从编辑文本中获取输入并将其插入futureDate.setHours(i); futureDate.setMinutes(J); 对? (2认同)

Pau*_*bra 6

我正要走出办公室,所以毫无疑问有人可以添加更详细的答案,但你需要使用AlarmManager

Alarm Manager适用于您希望在特定时间运行应用程序代码的情况,即使您的应用程序当前未运行也是如此.