意外的应用程序崩溃

时间:2012-07-11 13:38:25

标签: android crash messenger

我尝试创建一个服务客户端应用程序(仍在学习这些)。 我的应用程序从一开始就崩溃了,不让我做任何事情。 任何想法如何弄清楚? 这是我的2个类和清单文件。

////////////////// 1. MainActivity.java //////////////////////

public class MainActivity extends Activity {

/** Messenger for communicating with the service. */
Messenger mService = null;

/** Flag indicating whether we have called bind on the service. */
boolean mBound;

/**
 * Handler of incoming messages from service.
 */
static class IncomingHandler extends Handler {
    private TextView mCallbackText;

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MessengerService.MSG_SET_VALUE:
                mCallbackText.setText("Received from service: " + msg.arg1);
                break;
            default:
                super.handleMessage(msg);
        }
    }
}

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

public void sayHello(View v) {
    if (!mBound) return;
    // Create and send a message to the service, using a supported 'what' value
    Message msg = Message.obtain(null, MessengerService.MSG_REGISTER_CLIENT, 0, 0);
    try {
        msg.replyTo = mMessenger;
        mService.send(msg);
    } catch (RemoteException e) {
        e.printStackTrace();
    }
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

@Override
protected void onStart() {
    super.onStart();
    // Bind to the service
    bindService(new Intent(this, MessengerService.class), mConnection,
        Context.BIND_AUTO_CREATE);
    mBound = true;
}

@Override
protected void onStop() {
    super.onStop();
    // Unbind from the service
    if (mBound) {
        unbindService(mConnection);
        mBound = false;
    }
}

/**
 * Class for interacting with the main interface of the service.
 */
private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
        // This is called when the connection with the service has been
        // established, giving us the object we can use to
        // interact with the service.  We are communicating with the
        // service using a Messenger, so here we get a client-side
        // representation of that from the raw IBinder object.
        mService = new Messenger(service);
        mBound = true;
        /*try {
            Message msg = Message.obtain(null,
                    MessengerService.MSG_REGISTER_CLIENT);
            msg.replyTo = mMessenger;
            mService.send(msg);

            // Give it some value as an example.
            msg = Message.obtain(null,
                    MessengerService.MSG_SET_VALUE, this.hashCode(), 0);
            mService.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }*/

    }

    public void onServiceDisconnected(ComponentName className) {
        // This is called when the connection with the service has been
        // unexpectedly disconnected -- that is, its process crashed.
        mService = null;
        mBound = false;
    }
};

}

/////////////////// 2. MessengerService.java /////////////////////// /

public class MessengerService extends Service {

String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNM = (NotificationManager) getSystemService(ns);

/** Command to the service to display a message */
static final int MSG_SAY_HELLO = 1;
/** Command to the service to register a client */
static final int MSG_REGISTER_CLIENT = 1;
/** Command to the service to unregister a client */
static final int MSG_UNREGISTER_CLIENT = 2;
/** Command to the service to set a new value */
static final int MSG_SET_VALUE = 3;

static class IncomingHandler extends Handler {
    private ArrayList<Messenger> mClients = new ArrayList<Messenger>();
    private int mValue=0;

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_REGISTER_CLIENT:
                mClients.add(msg.replyTo);
                break;
            case MSG_UNREGISTER_CLIENT:
                mClients.remove(msg.replyTo);
                break;
            case MSG_SET_VALUE:
                mValue = msg.arg1;
                for (int i=mClients.size()-1; i>=0; i--) {
                    try {
                        mClients.get(i).send(Message.obtain(null,
                                MSG_SET_VALUE, mValue, 0));
                    } catch (RemoteException e) {
                        // The client is dead.  Remove it from the list;
                        // we are going through the list from back to front
                        // so this is safe to do inside the loop.
                        mClients.remove(i);
                    }
                }
                break;
            default:
                super.handleMessage(msg);
        }
    }
}

final Messenger mMessenger = new Messenger(new IncomingHandler());

public void onCreate() {
    mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

    // Display a notification about us starting.
    showNotification();
    //handleMessage(msg);
}

@Override
public void onDestroy() {
    // Cancel the persistent notification.
    mNM.cancel(R.string.remote_service_started);

    // Tell the user we stopped.
    Toast.makeText(this, R.string.remote_service_stopped, Toast.LENGTH_SHORT).show();
}

@Override
public IBinder onBind(Intent intent) {
    Toast.makeText(getApplicationContext(), "Binding..", Toast.LENGTH_SHORT).show();
    return mMessenger.getBinder();
}

private void showNotification() {
    // Set icon, scrolling text, etc
    int icon = R.drawable.asd;
    CharSequence tickerText = "Hello!";
    CharSequence text = getText(R.string.remote_service_started);
    long when = System.currentTimeMillis();
    Context context = getApplicationContext();

    //Create notication with parameters
    Notification.Builder nFN = new Notification.Builder(context)
                                                .setTicker(tickerText)
                                                .setWhen(when)
                                                .setSmallIcon(icon)
                                                .setContentTitle("Test Notifications")
                                                .setContentText(text)
                                                .setAutoCancel(true);

    // The PendingIntent to launch our activity if the user selects this notification
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MessengerService.class), 0);
    nFN.setContentIntent(contentIntent);

    // Send the notification.
    Notification n = nFN.build();
    mNM.notify(R.string.remote_service_started, n);
}

}

/////////////////// 3.清单///////////////////////// ////////////

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.praktiki.services.messenger"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="16"
    android:targetSdkVersion="15" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <service 
        android:name=".MessengerService"
        android:process=":remote"
         />

    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

1 个答案:

答案 0 :(得分:0)

我认为您忘记初始化您正在使用的TextView

mCallbackText.setText("Received from service: " + msg.arg1);

如果不引用实际字段,上面的行会产生NullPointerException,因此请将以下行添加到onCreate(Bundle)

mCallbackText = (TextView) findViewById(R.id.my_textview);

编辑:

请注意,您需要以您选择的方式将其传递给您的处理程序。