Android从服务类调用IntentService类

时间:2016-05-07 19:45:25

标签: android nullpointerexception android-service android-context android-intentservice

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

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

我在服务类中使用上面的代码行来启动IntentService类。但后来我得到了以下错误: -

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)

**编辑:------------- **

1。主要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 个答案:

答案 0 :(得分:1)

我今天已经回答了另一个question的错误。

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

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

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

导致空指针,因为'this'为null。 (为什么?因为这是指由于未使用startService(intent)启动服务而尚未创建的上下文)

顺便说一下,我不明白为什么要从服务中启动意向服务。您可以像这样

从DataProviderObserver类中执行此操作
Intent MyIntentService = new Intent(context, MyIntentService.class);
context.startService(MyIntentService);

因为班级中存在上下文。