我的配置如下
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android_sync.service" android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<receiver android:name="ServiceStartReceiver">
<intent-filter>
<action android:name="NotifyServiceStart"></action>
</intent-filter>
</receiver>
<receiver android:name="ServiceStopReceiver">
<intent-filter>
<action android:name="NotifyServiceStop"></action>
</intent-filter>
</receiver>
<service android:name="AndroidSyncService">
<intent-filter>
<action android:name="SyncService"></action>
</intent-filter>
</service>
</application>
</manifest>
public class AndroidSyncService extends Service{
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
Log.d("TAG", "onCreate22222222222222-----------------");
}
public void onDestroy() {
Log.d("TAG", "onDestroy222222222222-----------------");
stopSocket();
}
public void onStart(Intent intent, int startId) {
Log.d("TAG", "onStart222222222222-----------------");
startSocket();
}
}
public class ServiceStartReceiver extends BroadcastReceiver {
// private static String SERVICE_START = "NotifyServiceStart";
private static String TAG = "____sync";
private static String SYNC_SERVICE = "SyncService";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "service start!--------");
Intent service = new Intent(SYNC_SERVICE);
context.startService(service);
}
}
public class ServiceStopReceiver extends BroadcastReceiver {
// private static String SERVICE_STOP = "NotifyServiceStop";
private static String TAG = "____sync";
private static String SYNC_SERVICE = "SyncService";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "service stop!--------");
Intent service = new Intent(SYNC_SERVICE);
context.stopService(service);
}
}
在命令行下发送广播:
adb shell am broadcast -a NotifyServiceStart
adb shell am broadcast -a NotifyServiceStop