Android绑定服务问题

时间:2013-10-05 18:23:06

标签: java android

我不明白为什么plainText = mService.getPlainText(key, cipherText);类中的crackingProcess会导致错误。如果我将该行放在buttonclick中,它就可以了。任何人都可以向我解释有什么问题吗?

public class CrackingProcess extends Activity {

TextView message;
TextView result;
DesService mService;
boolean mBound = false;
Button btnStop;
String[] stringResult;
String key;
String cipherText;
String plainText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cracking_process);

    message = (TextView) findViewById(R.id.message);
    btnStop = (Button) findViewById(R.id.btnStop);
    result = (TextView) findViewById(R.id.result);
    message.setText("Cracking In Progress...");

    doBindService();
}

@Override
protected void onStart() {
    super.onStart();

    try {       
        AssetManager fileManager = getAssets();
        InputStream fileInput = fileManager.open("json_block56");
        Reader fileRead = new InputStreamReader(fileInput);
        JsonReader reader = new JsonReader(fileRead);

        stringResult = readJson(reader);

        key = stringResult[1];
        Log.d("key", key);
        cipherText = stringResult[2];
        Log.d("text", cipherText);

        plainText = mService.getPlainText(key, cipherText); // This line cause error
        result.setText(plainText);

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


    btnStop.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {    
            if (mBound) {
                unbindService(mConnection);
                mBound = false;
            }
            finish();
        }
    });
}

private String[] readJson(JsonReader reader) throws IOException {
    String[] array = new String[3];
    String type = "";
    String key = "";
    String cipherText = "";
//  ArrayList<String> result = null;

    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals("reply")) {
            reader.beginObject();
            while (reader.hasNext()) {
                String newName = reader.nextName();
                if (newName.equals("type"))
                    type = reader.nextString();
                else if (newName.equals("key"))
                    key = reader.nextString();
                else if (newName.equals("ciphertext"))
                    cipherText = reader.nextString();
                else
                    reader.skipValue();
            }
            reader.endObject();
        } else
            reader.skipValue();
    }
    reader.endObject();

    array[0] = type;
    array[1] = key;
    array[2] = cipherText;

    return array;
}

public ServiceConnection mConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        mService = ((DesService.LocalBinder)service).getService();
        mBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        mService = null;
        //mBound = false;
    }

};

void doBindService() {
    Intent intent = new Intent(this, DesService.class);
    startService(intent);
    boolean bound = bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

    if ( bound ) {
        Log.d( "Sucess", "Successfully bound to service" );
    }
    else {
        Log.d( "Fail", "Failed to bind service" );
    }
}

}

DESService类

public class DesService extends Service {

private final IBinder mBinder = new LocalBinder();

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    return super.onStartCommand(intent, flags, startId);
}

public class LocalBinder extends Binder {

    public DesService getService() {
        return DesService.this;
    }

}

public String getPlainText(String key, String cipherText) {
     return "testing";  
}  

}

logcat的

10-05 18:29:13.893: D/AndroidRuntime(8026): Shutting down VM
10-05 18:29:13.893: W/dalvikvm(8026): threadid=1: thread exiting with uncaught exception (group=0xa62c5288)
10-05 18:29:13.897: E/AndroidRuntime(8026): FATAL EXCEPTION: main
10-05 18:29:13.897: E/AndroidRuntime(8026): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.androiddes/com.example.androiddes.CrackingProcess}: java.lang.NullPointerException
10-05 18:29:13.897: E/AndroidRuntime(8026):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at android.os.Looper.loop(Looper.java:137)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at android.app.ActivityThread.main(ActivityThread.java:4745)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at java.lang.reflect.Method.invokeNative(Native Method)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at java.lang.reflect.Method.invoke(Method.java:511)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at dalvik.system.NativeStart.main(Native Method)
10-05 18:29:13.897: E/AndroidRuntime(8026): Caused by: java.lang.NullPointerException
10-05 18:29:13.897: E/AndroidRuntime(8026):     at com.example.androiddes.CrackingProcess.onStart(CrackingProcess.java:63)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1163)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at android.app.Activity.performStart(Activity.java:5018)
10-05 18:29:13.897: E/AndroidRuntime(8026):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2032)
10-05 18:29:13.897: E/AndroidRuntime(8026):     ... 11 more

3 个答案:

答案 0 :(得分:1)

尽管方法bindService()返回true,但尚未建立与服务的实际连接。

绑定到不同进程(IPC)的服务是异步的。在调用onServiceConnected()之前,您无法使用该服务。 onStart()在此过程中为时尚早,这就是为什么mServicenull

这也解释了为什么将代码放在按钮单击侦听器中的原因。当您点击按钮时,连接已建立。

答案 1 :(得分:0)

当您在其上调用mService方法时,看起来您的getPlainText对象未初始化,从而导致空指针异常。

getPlainText初始化mService之后,等待致电OnServiceConnected

答案 2 :(得分:0)

来自bindService()的肯定结果意味着您获得服务。它并不意味着它已经发生,因此mService将为空。

您的问题专栏plainText = mService.getPlainText(key, cipherText);只能在onServiceConnected()之后或之内 - onServiceDisconnected()之前工作。