Android 从服务类调用 IntentService 类 [英] Android calling IntentService class from a Service Class

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

问题描述

我们可以从正在运行的服务类调用 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.主Activity.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 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆