定期执行警报(自动启动)

时间:2012-12-12 13:53:15

标签: android alarmmanager

我研究了自己的应用程序的alarmmanager和autostart。我想要一个看不见的服务(这不是正确的名字,对不起),它定期向我展示一个祝酒词(用于测试目的)。

以下代码运行但未正确运行。我点击“按钮”,活动消失但没有...

我的代码:

MainActivity

public class MainActivity extends Activity {

/** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Button buttonStart = (Button)findViewById(R.id.button1);
      buttonStart.setOnClickListener(new Button.OnClickListener(){

  @Override
  public void onClick(View arg0) {
    Intent myIntent = new Intent(getBaseContext(),
      MyScheduledReceiver.class);

    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, 10);
    long interval = 60 * 10; //
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
      calendar.getTimeInMillis(), interval, pendingIntent);
    finish();
  }});
  }

}


AutoStartNotifyReceiver

public class AutoStartNotifyReceiver extends BroadcastReceiver {
    private final String BOOT_COMPLETED_ACTION =   "android.intent.action.BOOT_COMPLETED";
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals(BOOT_COMPLETED_ACTION)){

             Intent myIntent = new Intent(context, MyScheduledReceiver.class);
             PendingIntent pendingIntent = PendingIntent.getBroadcast(context,  0,     myIntent, 0);

             AlarmManager alarmManager =         (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
             Calendar calendar = Calendar.getInstance();
             calendar.setTimeInMillis(System.currentTimeMillis());
             calendar.add(Calendar.SECOND, 10);
             long interval = 60 * 10;
             alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,         calendar.getTimeInMillis(), interval, pendingIntent);           
        }
    }
}

MyScheduledActivity

public class MyScheduledActivity extends Activity {

MediaPlayer player;

@Override
public void onCreate(Bundle savedInstanceState){ 
  super.onCreate(savedInstanceState);
  //Toast.makeText(getApplicationContext(), "Eseguo onCreate",     Toast.LENGTH_LONG).show();
  setContentView(R.layout.activity_main);

  player = MediaPlayer.create(this, R.raw.gabriel);
  player.start();



    Toast.makeText(this, "miao",Toast.LENGTH_LONG).show();

}

 }

 MyScheduledReceiver

 public class MyScheduledReceiver extends BroadcastReceiver {

 public void onReceive(Context context, Intent intent) {

 Intent scheduledIntent = new Intent(context, MyScheduledActivity.class);
 scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 context.startActivity(scheduledIntent);
 }
 }

清单:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name=".AutoStartNotifyReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>

{12-12 14:50:21.411:E / AndroidRuntime(865):致命异常:主要 12-12 14:50:21.411:E / AndroidRuntime(865):java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.servi / com.example.servi.M​​yScheduledActivity}:java.lang.NullPointerException 12-12 14:50:21.411:E / AndroidRuntime(865):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956) 12-12 14:50:21.411:E / AndroidRuntime(865):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 12-12 14:50:21.411:E / AndroidRuntime(865):在android.app.ActivityThread.access $ 600(ActivityThread.java:123) 12-12 14:50:21.411:E / AndroidRuntime(865):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1147) 12-12 14:50:21.411:E / AndroidRuntime(865):在android.os.Handler.dispatchMessage(Handler.java:99) 12-12 14:50:21.411:E / AndroidRuntime(865):在android.os.Looper.loop(Looper.java:137) 12-12 14:50:21.411:E / AndroidRuntime(865):在android.app.ActivityThread.main(ActivityThread.java:4424) 12-12 14:50:21.411:E / AndroidRuntime(865):at java.lang.reflect.Method.invokeNative(Native Method) 12-12 14:50:21.411:E / AndroidRuntime(865):at java.lang.reflect.Method.invoke(Method.java:511) 12-12 14:50:21.411:E / AndroidRuntime(865):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:784) 12-12 14:50:21.411:E / AndroidRuntime(865):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 12-12 14:50:21.411:E / AndroidRuntime(865):at dalvik.system.NativeStart.main(Native Method) 12-12 14:50:21.411:E / AndroidRuntime(865):引起:java.lang.NullPointerException 12-12 14:50:21.411:E / AndroidRuntime(865):at com.example.servi.M​​yScheduledActivity.onCreate(MyScheduledActivity.java:22) 12-12 14:50:21.411:E / AndroidRuntime(865):在android.app.Activity.performCreate(Activity.java:4465) 12-12 14:50:21.411:E / AndroidRuntime(865):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 12-12 14:50:21.411:E / AndroidRuntime(865):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920) 12-12 14:50:21.411:E / AndroidRuntime(865):... 11更多 }

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.servi"
android:versionCode="1"
android:versionName="1.0" >

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="16" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.servi.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

<receiver android:name=".AutoStartNotifyReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>
<receiver android:name="MyScheduledReceiver"></receiver>
<activity android:name="MyScheduledActivity"></activity>
</application>
</manifest>

2 个答案:

答案 0 :(得分:1)

来自http://www.androidsnippets.com/autostart-an-application-at-bootup

AndroidManifest.xml中的

(应用程序部分):

<receiver android:enabled="true" android:name=".BootUpReceiver"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">

        <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
</receiver>
[..]
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
[..]

public class BootUpReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
                Intent i = new Intent(context, MyActivity.class);  
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);  
        }

}

您可以使用Timer类来使用TimerTask安排定期任务。您也可以使用ScheduledThreadPoolExecutor类。

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

答案 1 :(得分:0)

在清单中添加接收器...以便接收警报。 在你的情况下;

<receiver android:name=".MyScheduledReceiver">

</receiver>

我希望它能解决问题

PS:你的活动MyScheduledActivity几乎每隔600毫秒就会重复启动两次......所以不要这样做......增加间隔:) 或者做任何其他事情来检查打印日志或某些东西进行测试