本文介绍了Android从服务类调用IntentService类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以从运行中的Service类调用IntentService类吗?

Can we call IntentService class from a running Service class .

Intent myintentservice = new Intent(this, MyIntentService.class);
startService(myintentservice);

我使用服务类中的上述代码行来启动IntentService类.但随后出现以下错误:-

I using above lines of code in service class to start IntentService class. But then I get following error:-

Process: objectdistance.ankeshkjaisansaria.ram.sita.cameratag, PID: 21823


java.lang.NullPointerException: Attempt to invoke virtual method

'java.lang.String android.content.Context.getPackageName()' on a null object reference


at android.content.ComponentName.<init>(ComponentName.java:77)


at android.content.Intent.<init>(Intent.java:4161)

**------------- **

**Edited:------------- **

1.主要活动.Java

OnCreate():-

OnCreate():-

Intent i = new Intent(this, ServiceA.class);
startService(i);

2. ServiceA.java

public class ServiceA extends Service {


    String TAG = "Log";
    private static HandlerThread sWorkerThread;
    private static Handler sWorkerQueue;
    private static DataProviderObserver sDataObserver;

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

    @Override
    public void onCreate() {
        sWorkerThread = new HandlerThread("ContentObserver");
        sWorkerThread.start();
        sWorkerQueue = new Handler(sWorkerThread.getLooper());

        final ContentResolver r = this.getContentResolver();
        if (sDataObserver == null) {
            sDataObserver = new DataProviderObserver(getApplicationContext(), sWorkerQueue);
            Log.d("CP", " " + android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            r.registerContentObserver(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true, sDataObserver);

        }
        else{Log.d("Error","Error Content Observer Service");}

        super.onCreate();
    }

    public void IntService(){

        Intent MyIntentService = new Intent(this, MyIntentService.class);
        startService(MyIntentService);

    }

    @Override
    public void onDestroy() {
        getContentResolver().unregisterContentObserver(sDataObserver);
        super.onDestroy();
    }


}

3. DataProviderObserver.Class

public class DataProviderObserver extends ContentObserver {

    Context context;

    DataProviderObserver(Context context ,Handler h) {
        super(h);
        this.context = context;

    }


    @Override
    public void onChange(boolean selfChange, Uri uri) {
        if (uri.toString().equals("content://media/external/images/media")){
            ServiceA  obj1 = new ServiceA();
            ob1.IntService();
        }
    }

    @Override
    public boolean deliverSelfNotifications() {
        return false;
    }



}

4. MyIntentService.java

public class MyIntentService extends IntentService {
Context ctx;

public MyIntentService() {
    super("test-service");
}

@Override
public void onCreate() {
    ctx = getBaseContext();
    super.onCreate();
}
@Override
public void onHandleIntent(Intent i){

         try {

        Uri uri;
        Cursor cursor;
        int column_index_id , column_index_data;
        uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        String order = MediaStore.MediaColumns.DATE_ADDED + " desc";
        String[] projection = {MediaStore.MediaColumns._ID , MediaStore.MediaColumns.DATA};
        cursor = **CONTEXT_REQUIRED**.getContentResolver().query(uri, projection, null, null, order);


        column_index_id = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID);
        column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);

        cursor.close();


    }catch (Exception e){
        e.printStackTrace();
    }

 // My Task
 }

}

推荐答案

我已经回答了另一个,它具有完全相同的错误.

I have answered another question today which has exactly the same mistake.

ServiceA  obj1 = new ServiceA();
ob1.IntService();

您正在尝试创建服务的新对象,这是非常非常糟糕的做法.您不能简单地创建这样的服务对象. Android中的所有服务都必须经历服务生命周期,以便它们具有有效的上下文.在这种情况下,有效上下文不会附加到obj1实例.因此,结果行

You are trying to create a new object of a service which is a very very bad practice. You cannot simply create an object of service like this. All Services in Android must go through the Service lifecycle so that they have a valid context attached to them. In this case a valid context is not attached to the obj1 instance. So as a result the line

Intent MyIntentService = new Intent(this, MyIntentService.class);

导致空指针,因为"this"为空. (为什么?因为这是指尚未创建的上下文,因为未使用startService(intent)启动该服务)

causes a null pointer as 'this' is null. (Why? Because this refers to the context which has not yet been created as the service is not started using startService(intent))

顺便说一句,我不明白为什么您要从服务内部启动意图服务.您可以像这样从DataProviderObserver类中轻松完成此操作

Btw I don't understand why you are starting the intent service from within the service. you can simply do it from the DataProviderObserver class like this

Intent MyIntentService = new Intent(context, MyIntentService.class);
context.startService(MyIntentService);

因为类中存在上下文.

这篇关于Android从服务类调用IntentService类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 21:37