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 上运行它

4

1 回答 1

1

您需要向您的应用程序添加一个活动,并且用户必须先手动启动该活动,然后您的应用程序才能在 Android 3.1+ 上运行。在那之前,你的<receiver>将被忽略。大约 9 个月前我在博客上写过这个

于 2012-04-19T14:22:26.863 回答