使用后台线程android从服务发送通知

时间:2015-04-06 09:08:58

标签: android multithreading android-service android-notifications

这是我的服务代码

public class MyService extends Service {
NotificationManager NM;
ServerSocket serversocket=null;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("","startcommand is called");



    return super.onStartCommand(intent, flags, startId);
}


private final IBinder binder=new MyBinder();



//this use for binding with activity
@Override
public IBinder onBind(Intent intent) {
    return binder;
}



//this class used by the Client to access the service
public class MyBinder extends Binder {
        public MyService getService(){
            return MyService.this;
        }
}






public void notify(){


    Notification notify=new Notification(android.R.drawable.ic_dialog_email,"Service is created",System.currentTimeMillis());
    Intent i=new Intent(this, MainActivity.class);
    i.putExtra("json","the notification method");
    PendingIntent pending=PendingIntent.getActivity(
            getApplicationContext(),0, i,0);
    notify.setLatestEventInfo(this,"subject","body",pending);
    NM.notify(0, notify);
}

@Override
public void onCreate() {
    ServerConnection serverConnection=new ServerConnection();
    serverConnection.execute();

}





public class ServerConnection extends AsyncTask<Void,String,Void>{

    @Override
    protected Void doInBackground(Void... params) {
        DataInputStream dataInputStream;

        try {
            serversocket = new ServerSocket(9100);
            while(true){

                Log.i("aa", "Service is listening to port");
                Socket socket =   serversocket.accept();


             NM = (NotificationManager)     getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
               publishProgress("ok");





            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    protected void onProgressUpdate(String... values) {
        notify();
    }


    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
    }





}

}

我不知道如果可以在服务中使用Asynctask,但无论如何每当我调用notify()发送通知时我都会收到错误

 java.lang.NullPointerException
        at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
        at android.content.ComponentName.<init>(ComponentName.java:75)
        at android.content.Intent.<init>(Intent.java:3301)
        at com.example.com.service.MyService.notify(MyService.java:76)
        at com.example.com.service.MyService$ServerConnection.onProgressUpdate(MyService.java:135)
        at com.example.com.service.MyService$ServerConnection.onProgressUpdate(MyService.java:95)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:647)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4745)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)

发送通知的notify()函数如果在onStartCommand中使用它或者在后台线程中除外,其他任何地方都可以正常工作。

我想要做的是每当我使用serversocket接收一些数据时,我想向不通用的用户发送通知。

感谢

1 个答案:

答案 0 :(得分:2)

检查这2行 -

    Intent i=new Intent(this, MainActivity.class);
   //// other lines
    notify.setLatestEventInfo(this,"subject","body",pending);

这里,this表示从asynctask调用方法时的asynctask,对吧?你应该尝试用MyService.this替换它。