Android定时自动启动应用程序 - 厕所蹲个猴

时间:2024-03-05 17:03:22

Android定时自动启动应用程序

使用AlarmManager搭配Receiver应该可以实现定时自动启动应用程序:

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class StartTiming extends Activity {
    
    public final String MYACTION = "android.intent.action.STARTMYAP";
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button btn = (Button)this.findViewById(R.id.btnClose);
        btn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                StartTiming.this.finish();
            }
        });
        AlarmManager am = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(MYACTION);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 1);
        am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+15000, pi);//15秒钟以后启动
    }
}
   
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class AlarmReceiver extends BroadcastReceiver
{
    public final String MYTAG = "Ray";
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        Log.v(MYTAG,"I am AlarmReceiver,I receive the message");
        Intent in = new Intent();
        in.setClass(context, StartTiming.class);
        in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(in);
    }
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.ray.test"
      android:versionCode="1"
      android:versionName="1.0" android:installLocation="auto">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".StartTiming"
                  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="AlarmReceiver">
               <intent-filter>
                 <action android:name="android.intent.action.STARTMYAP"/>
             </intent-filter>
        </receiver>
    </application>
</manifest>