如何从broadcastReceiver激活服务?

时间:2012-03-29 11:23:27

标签: android service broadcastreceiver

我想从broadcastReceiver激活一项服务,这是我的代码,但它不起作用:

public class PackageChangeReceiver extends BroadcastReceiver {
Context context;
Deletecontact delete= new Deletecontact();
@Override
public void onReceive(Context ctx, Intent intent) {
Uri uri = intent.getData();
String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
if(intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")&&   pkg.equals("com.alarm"))
{Log.i("action","the package is removed");
Intent service = new Intent( context, Deletecontact.class);
context.startService(service);
}}}

这是服务

     public void onCreate()
  {

     //deletecontact();
 super.onCreate();
 }

    @Override
 public int onStartCommand(Intent intent, int flags, int startId)
 {
    return START_STICKY;
 //return super.onStartCommand(intent, flags, startId);
 }

 @Override
 public void onDestroy()
 {
 super.onDestroy();
 }
@Override
public IBinder onBind(Intent arg0) {
    return mBinder;
}

public class MyBinder extends Binder {
    Deletecontact getService() {
        return Deletecontact.this;
    }
}

我只想在设置广播操作时调用该服务

2 个答案:

答案 0 :(得分:0)

@Emna当我看到您启动服务的代码时,您已使用此代码启动服务。

context.startService(service);

在此代码context中,这不会像下面那样分配

所以在致电startService

之前
 context=ctx;

onReceive之后添加上述代码。

并确保您已在AndroidManifest.xml中将此类定义为Deletecontact.class作为服务标记以下示例:

<service android:enabled="true" android:name="xxx.yyy.zzz.Deletecontact"
         ></service>

希望这会奏效。

答案 1 :(得分:0)

试试这个,使用ctx代替上下文来启动服务和准备Intent:

public class PackageChangeReceiver extends BroadcastReceiver {
Context context;
Deletecontact delete= new Deletecontact();
@Override
public void onReceive(Context ctx, Intent intent) {
Uri uri = intent.getData();
String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
if(intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")&&   pkg.equals("com.alarm"))
{Log.i("action","the package is removed");
Intent service = new Intent(ctx, Deletecontact.class);
ctx.startService(service);
}}}