1
我試圖學習如何在Android中創建服務,我做了一個非常簡單的服務。 問題在於,它在AVD上像是一種魅力,但在物理設備上卻不是。 只要它沒有啓動開機...服務啓動模擬器,但在設備上不是
看一看代碼:
的AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myservice" android:versionCode="1" android:versionName="1.0">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:icon="@drawable/ic_launcher" android:label="@string/app_name">
<receiver android:name=".ServiceStarter" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:enabled="true" android:name=".MyService" />
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
服務啓動:
package com.example.myservice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.example.myservice.MyService;
public class ServiceStarter extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())){
Intent pushIntent = new Intent(context, MyService.class);
//pushIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(pushIntent);
}
}
}
和服務它的自我:
package com.example.myservice;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
private static final String TAG = "MyService";
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
}
}
我在Android 4.0.3上運行它
很高興知道,thx m8! – mika 2012-04-19 15:04:21