Android calling IntentService class from a Service Class

旧巷老猫 提交于 2019-12-04 06:32:32

问题


Can we call IntentService class from a running Service class .

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

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. Main Activity.Java

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
 }

}

回答1:


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

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

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);

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))

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);

since context is present in the class.



来源:https://stackoverflow.com/questions/37092965/android-calling-intentservice-class-from-a-service-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!