POST

3089 ワード

携帯電話の電源を入れた後、すぐにサービスやアクティビティを開始する必要があることがよくあります.
 
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class AutoStartReceiver extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		Log.i("AS", " [AutoStartReceiver]");

		// 
		Intent bootIntent = new Intent(context, AutoStartActivity.class);
		bootIntent.setAction("android.intent.action.MAIN");
		bootIntent.addCategory("android.intent.category.LAUNCHER");
		bootIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(bootIntent);

		// 
		context.startService(new Intent(context, AutoStartService.class)); 
	}
}

 
 
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class AutoStartService extends Service {
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i("AS", " [AutoStartService]");
		return 0;
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
}
 
 
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

/**
 *  
 * @author Davee
 */
public class AutoStartActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	Log.i("AS", " [AutoStartActivity]");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.aotu_start);
    }
}
 
 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  <TextView android:layout_width="fill_parent"
  	android:layout_height="fill_parent"
  	android:text=" Activity" />
</LinearLayout>

 
権限の追加
 
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
 
構成の追加
 
<activity android:name=".AutoStartActivity" />
<service android:name=".AutoStartService" />
<receiver android:name=".AutoStartReceiver" >
	<intent-filter>
		<!--   -->
		<action android:name="android.intent.action.BOOT_COMPLETED"/>  
        	<category android:name="android.intent.category.HOME" />
	</intent-filter>
</receiver>