我刚刚开始Android开发并遇到了这个问题。我试图在特定时间后开始一个意图。
我尝试将Intent放在Runnable中,使用runnable和handler.postAtTime方法。当您销毁应用程序或重新启动手机时,此方法不执行任何操作。
我尝试设置一个BroadcastReceiver,但它不允许我对Intent使用startActivity(Intent)。我尝试使用Context.startActivity(Intent),但如果它在Intent完成之前被销毁,它会使应用停止工作。
任何人都能帮助我吗?感谢。
Edit1:
这是我使用AlarmManager调用的BroadcastReceiver:
package com.mallock.sch_email2;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.Toast;
public class Broadcast extends BroadcastReceiver{
@Override
public void onReceive(Context arg0, Intent arg1) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, Activity1.subj);
intent.putExtra(Intent.EXTRA_TEXT, Activity1.body);
intent.setData(Uri.parse("mailto:".concat(Activity1.rec)));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(arg0,intent);
Toast.makeText(arg0, "I'm running", Toast.LENGTH_SHORT).show();
}
}
logcat:
07-15 21:43:13.980 4569-4569/com.mallock.sch_email2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.mallock.sch_email2, PID: 4569
java.lang.RuntimeException: Unable to start receiver com.mallock.sch_email2.Broadcast: java.lang.NullPointerException
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2580)
at android.app.ActivityThread.access$1700(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
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:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at java.lang.String.concat(String.java:678)
at com.mallock.sch_email2.Broadcast.onReceive(Broadcast.java:16)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2573)
at android.app.ActivityThread.access$1700(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
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:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:1)
此class适合您! AlarmManager是正确的方法。
答案 1 :(得分:0)
我正在使用PendingIntent.getBroadcast,然后使用BroadcastReceiver启动一个Intent。直接使用PendingIntent.getActivity解决了这个问题。
@Mimmo Grottoli:正确......谢谢:)