`

Android 之开机启动Service

阅读更多
配置文件如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="net.blogjava.mobile.startupservice" android:versionCode="1"
	android:versionName="1.0">
	<application android:icon="@drawable/icon" android:label="@string/app_name">
	    
		<activity android:name=".MessageActivity" 
		     android:theme="@android:style/Theme.Dialog">
			<intent-filter>				
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>
	
		<receiver android:name="StartupReceiver">
			<intent-filter>
				<action android:name="android.intent.action.BOOT_COMPLETED" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</receiver>
		<service android:enabled="true" android:name=".MyService" />
	</application>
	<uses-sdk android:minSdkVersion="3" />
	<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</manifest> 




定义广播接收器:
public class StartupReceiver extends BroadcastReceiver
{
	@Override
	public void onReceive(Context context, Intent intent)
	{
		Intent serviceIntent = new Intent(context, MyService.class);		
		context.startService(serviceIntent);		
		
		Intent activityIntent = new Intent(context, MessageActivity.class);
//要想在Service中启动Activity ,必须设置如下标志
		activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(activityIntent);
	}

}


定义后台服务类:

public class MyService extends Service
{

	@Override
	public IBinder onBind(Intent intent)
	{
		return null;
	}

	@Override
	public void onCreate()
	{
		Log.d("StartUpMyService", "onCreate");
		super.onCreate();
	}

	@Override
	public void onDestroy()
	{
		Log.d("StartUpMyService", "onDestroy");
		super.onDestroy();
	}

	@Override
	public void onStart(Intent intent, int startId)
	{
		Log.d("StartUpMyService", "onStart");
		super.onStart(intent, startId);
	}
}


定义绑定的Activity

public class MessageActivity extends Activity
{

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.message);
	}

}
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics