0

对不起我的英语不好

我有一个通过 Messenger 与服务通信的活动。当我启动 Activity 并按下使 unbindservice 没有首先进行 bindservice 的按钮时,我的应用程序向我发送 NullPointerException 并且我的 Activity 崩溃。

日志猫。

6-30 20:38:26.802: E/AndroidRuntime(29453): FATAL EXCEPTION: main
06-30 20:38:26.802: E/AndroidRuntime(29453): java.lang.NullPointerException
06-30 20:38:26.802: E/AndroidRuntime(29453):    at com.example.servicetest.MainActivity.doUnbindService(MainActivity.java:180)
06-30 20:38:26.802: E/AndroidRuntime(29453):    at com.example.servicetest.MainActivity$3.onClick(MainActivity.java:109)
06-30 20:38:26.802: E/AndroidRuntime(29453):    at android.view.View.performClick(View.java:4261)
06-30 20:38:26.802: E/AndroidRuntime(29453):    at android.view.View$PerformClick.run(View.java:17356)
06-30 20:38:26.802: E/AndroidRuntime(29453):    at android.os.Handler.handleCallback(Handler.java:615)
06-30 20:38:26.802: E/AndroidRuntime(29453):    at android.os.Handler.dispatchMessage(Handler.java:92)
06-30 20:38:26.802: E/AndroidRuntime(29453):    at android.os.Looper.loop(Looper.java:137)
06-30 20:38:26.802: E/AndroidRuntime(29453):    at android.app.ActivityThread.main(ActivityThread.java:4921)
06-30 20:38:26.802: E/AndroidRuntime(29453):    at java.lang.reflect.Method.invokeNative(Native Method)
06-30 20:38:26.802: E/AndroidRuntime(29453):    at java.lang.reflect.Method.invoke(Method.java:511)
06-30 20:38:26.802: E/AndroidRuntime(29453):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
06-30 20:38:26.802: E/AndroidRuntime(29453):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
06-30 20:38:26.802: E/AndroidRuntime(29453):    at dalvik.system.NativeStart.main(Native Method)
06-30 20:38:26.852: E/android.os.Debug(2019): !@Dumpstate > dumpstate -k -t -z -d -o  /data/log/dumpstate_app_error

我的活动代码。

public class MainActivity extends Activity {
 /** Messenger for communicating with the service. */
Messenger mService = null;
Boolean mBound;
Button button1,button2,button3,button4,button5,button6;
Intent intent_serv;


private ServiceConnection mConnection = new ServiceConnection() {

    public void onServiceConnected(ComponentName className, IBinder service) {

        mService = new Messenger(service);
        mBound=true;
        Toast.makeText(getBaseContext(), "Conectado-Binding",Toast.LENGTH_SHORT).show();
    }

    public void onServiceDisconnected(ComponentName className) {
        // This is called when the connection with the service has been unexpectedly disconnected - process crashed.
        mService = null;
        mBound=false;
        Toast.makeText(getBaseContext(), "Desconectado-Unbinding",Toast.LENGTH_SHORT).show();
    }
};






@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button1=(Button)findViewById(R.id.button1);
    button2=(Button)findViewById(R.id.button2);
    button3=(Button)findViewById(R.id.button3);
    button4=(Button)findViewById(R.id.button4);
    button5=(Button)findViewById(R.id.button5);
    button6=(Button)findViewById(R.id.button6);



    button1.setOnClickListener(new OnClickListener() {
        //start Service
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Log.i("PruebaService", "Boton Start Service");
            // Bind to the service
            intent_serv=new Intent(MainActivity.this, PruebaService.class);
            startService(intent_serv);


        }
    });
    button2.setOnClickListener(new OnClickListener() {
        //Stop Service
        @Override
        public void onClick(View v) {
            Log.i("PruebaService", "Boton Parar Service");
            // TODO Auto-generated method stub

            intent_serv=new Intent(MainActivity.this,PruebaService.class);
            stopService(intent_serv);
        }
    });
    button3.setOnClickListener(new OnClickListener() {
        // Bind service.
        @Override
        public void onClick(View v) {
            Log.i("PruebaService", "Boton Bind Service");
            // TODO Auto-generated method stub
            MainActivity.this.bindService(intent_serv, mConnection,Context.BIND_AUTO_CREATE);

        }
    });

    button4.setOnClickListener(new OnClickListener() {
        // Unbind service.
        @Override
        public void onClick(View v) {
            Log.i("PruebaService", "Boton Unbound-Status mBound:"+mBound);
            // TODO Auto-generated method stub

             if (mBound) {
                    MainActivity.this.unbindService(mConnection);
                    mBound = false;
                }else{
                    Log.i("PruebaService", "PAso al Else.");
                }

        }
    });

    button5.setOnClickListener(new OnClickListener() {
        // Bind service.

        @Override
        public void onClick(View v) {
            Log.i("PruebaService", "Boton message to service 1");
            // TODO Auto-generated method stub

        }
    });

    button6.setOnClickListener(new OnClickListener() {
        // Bind service.
        @Override
        public void onClick(View v) {
            Log.i("PruebaService", "Boton message to service 10");


        }
    });




}
@Override
protected void onDestroy() {
    super.onStop();
    Log.i("PruebaService", "Estado mBound :"+mBound+"Estado mConnection :"+mConnection);
    // Unbind from the service
    if (mBound && mConnection!=null) {
        MainActivity.this.unbindService(mConnection);
        mBound = false;
    }
}

我的服务代码。

public class PruebaService extends Service{
private NotificationManager nm;



static final int MSG_REGISTER_CLIENT = 1;
static final int MSG_UNREGISTER_CLIENT = 2;
static final int MSG_SET_INT_VALUE = 3;
static final int MSG_SET_STRING_VALUE = 4;
static final int MSG_SET_RESP_A = 5;
static final int MSG_SET_RESP_B = 6;

final Messenger mMessenger = new Messenger(new IncomingHandler()); // Target we publish for clients to send messages to IncomingHandler.


@Override
public IBinder onBind(Intent intent) {
    return mMessenger.getBinder();
}
class IncomingHandler extends Handler { // Handler of incoming messages from clients.
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {

        case MSG_SET_RESP_A:
            //incrementby = msg.arg1;
            break;
        case MSG_SET_RESP_B:
           // incrementby = msg.arg1;
            break;
        default:
            super.handleMessage(msg);
        }
    }
}


@Override
public void onCreate() {
    super.onCreate();
    Log.i("PruebaService", "Service Started.");
    showNotification();
    //timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 0, 100L);

}
private void showNotification() {
    nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    // In this sample, we'll use the same text for the ticker and the expanded notification
    CharSequence text = getText(R.string.service_started);
    // Set the icon, scrolling text and timestamp
    Notification notification = new Notification(R.drawable.advertencia, text, System.currentTimeMillis());
    // The PendingIntent to launch our activity if the user selects this notification
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
    // Set the info for the views that show in the notification panel.
    notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent);
    // Send the notification.
    // We use a layout id because it is a unique number.  We use it later to cancel.
    nm.notify(R.string.service_started, notification);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("PruebaService", "Received start id " + startId + ": " + intent);
    return START_STICKY; // run until explicitly stopped.
}




@Override
public void onDestroy() {
    super.onDestroy();
    //if (timer != null) {timer.cancel();}
    nm.cancel(R.string.service_started); // Cancel the persistent notification.
    Log.i("PruebaService", "Service Stopped.");


}

我希望你能帮助我解决我的问题。

4

0 回答 0