为什么在启动绑定服务android时出现空指针异常 [英] Why null pointer exception appear when start bound service android

查看:90
本文介绍了为什么在启动绑定服务android时出现空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我做得很好,但我不知道为什么会出现这种情况

这个MainActivity.java代码

  package  com.smarty_tech.boundservice; 

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;


public class MainActivity extends AppCompatActivity {
private static 字符串 LOG_TAG = MainActivity;

private Button btnStartService;
private 按钮btnStopService;

SmartyService服务;
boolean mBound = false;

@ Override
protected void onCreate(Bundle savedInstanceState){
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Intent intent = new Intent(MainActivity。 this ,SmartyService。 class );
btnStartService =(Button)findViewById(R.id.btn_start_service);
btnStopService =(Button)findViewById(R.id.btn_stop_service);



btnStartService.setOnClickListener( new View.OnClickListener(){
@ Override
public void onClick(查看视图) {
bindService(intent,connection,Service.BIND_AUTO_CREATE);
// service.printHelloWorld( );
int x = service.getRandomNumber();
Log.e( 启动绑定服务 绑定Successfuly和X值是);
}
});

btnStopService.setOnClickListener( new View.OnClickListener(){
@ Override
public void onClick(查看视图){
unbindService(connection );
Log.e( Start Bound Service UnBounded Successfuly);
}
});

}

/ * *定义服务绑定的回调,传递给bindService()* /
public ServiceConnection connection = new ServiceConnection( ){
@ Override
public void onServiceConnected(ComponentName className,IBinder服务){
// 我们必然会SmartyService,投射IBinder并获得SmartyService实例
SmartyService.SmartyBinder smartyBinder =(SmartyService.SmartyBinder)服务;
MainActivity。 this .service = smartyBinder.getService();
mBound = true;
Log.e(LOG_TAG, onServiceConnected call);
}

@覆盖
public void onServiceDisconnected(ComponentName className){
MainActivity。 this .service = null;
mBound = false;
Log.e(LOG_TAG, onServiceDisconnected call);
}
};
}





这是我的服务代码



  package  com.smarty_tech.boundservice; 

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import java.util.Random;

public class SmartyService extends 服务{
私有 静态 字符串 LOG_TAG = SmartyService;

public SmartyService(){
}

// 给予客户的活页夹
private 最终 IBinder binder = new SmartyBinder();
// 随机数生成器
private final 随机mGenerator = new Random();

/ * *
*用于客户Binder的类。因为我们知道这个服务总是
*在与客户端相同的进程中运行,所以我们不需要处理IPC。
* /

public class SmartyBinder extends Binder {
SmartyService getService(){
// 返回此LocalService实例,以便客户端可以调用公共方法
Log.v(LOG_TAG, 在SmartyBinder);
return SmartyService。 this ;
}
}

@覆盖
public IBinder onBind(意图意图){
// 抛出新的UnsupportedOperationException(尚未实现) ;
// printHelloWorld();
Log.v (on_档中的LOG_TAG, );
return binder;
}

@覆盖
public void onRebind(意图意图){
Log.v(LOG_TAG, in onRebind);
super .onRebind(intent);
}

@覆盖
public boolean onUnbind(Intent intent){
Log.v(LOG_TAG, in onUnind);
返回 true;
}

@覆盖
public void onCreate(){
super .onCreate();
Log.e(LOG_TAG, onCreated Called!);
}


@覆盖
public void onDestroy(){
super .onDestroy();
Log.e(LOG_TAG, onDestroy被叫,我会想你的!);
}

/ * *客户方法* /
public void printHelloWorld(){
// for(int i = 0; i< 1000; i ++){
Log.e(LOG_TAG, Hello Wolrd);
// }
}

/ * *客户端方法* /
public int getRandomNumber(){
return mGenerator.nextInt( 100 );
}
/ *

SmartyBinder提供getService()客户端检索SmartyService当前实例的方法。
这允许客户端调用服务中的公共方法。例如,客户端可以从服务中调用printHelloWorld()。
* /

}





这是布局的main_activity.xml



< pre><?xml version =   1.0 encoding =   utf-8?> 
< LinearLayout xmlns:android = http://schemas.android.com/apk/res/ android
xmlns:app = http://schemas.android.com/apk / res-auto
xmlns:tools = http://schemas.android。 com / tools
android:layout_width = match_parent
android:layout_height = match_parent
android:orientation = vertical
tools:context = MainActivity>

< Button
android:id = @ + id / btn_start_service
android:layout_width = wrap_content
android:layout_height = wrap_content
android:text = 启动服务
/>

< Button
android:id = @ + id / btn_stop_service
android:layout_width = wrap_content
android:layout_height = wrap_content
android:text = 停止服务
/>

< / LinearLayout>





我的尝试:



当我尝试启动服务时,Logcat上会出现以下异常



 06 -11 09:43:03.654 2380-2380 / com.smarty_tech.boundservice E / AndroidRuntime:FATAL EXCEPTION:main 
进程:com.smarty_tech.boundservice,PID:2380
java.lang.NullPointerException
在com.smarty_tech.boundservice.MainActivity $ 1.onClick(MainActivity.java:39)
在android.view.View.performClick(View.java:4438)
在android.view.View $ PerformClick.run(View.java:18422)
在android.os.Handler.handleCallback(Handler.java:733)
在android.os.Handler.dispatchMessage(Handler.java:95)
在android.os.Looper.loop(Looper.java:136)
在android.app.ActivityThread.main(ActivityThread.java:5019)
在java.lang.reflect.Method.invokeNative (本机方法)java.lang.reflect.Me中的
thod.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit。 main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)

解决方案

1。 onClick(MainActivity.java:39)
在android.view.View.performClick(View.java:4438)
在android.view.View


PerformClick。运行(View.java:18422)
在android.os.Handler.handleCallback(Handler.java:733)
在android.os.Handler.dispatchMessage(Handler.java:95)
在android.os.Looper.loop(Looper.java:136)
在android.app.ActivityThread.main(ActivityThread.java:5019)
at java.lang.reflect.Method.invokeNative(Native方法)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit


Method AndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)


I think i did everything well, but i don't know why this appear
This MainActivity.java Code

package com.smarty_tech.boundservice;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;


public class MainActivity extends AppCompatActivity {
    private static String LOG_TAG = "MainActivity";

    private Button btnStartService;
    private Button btnStopService;

    SmartyService service;
    boolean mBound = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Intent intent = new Intent(MainActivity.this, SmartyService.class);
        btnStartService = (Button) findViewById(R.id.btn_start_service);
        btnStopService = (Button) findViewById(R.id.btn_stop_service);



        btnStartService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               bindService(intent, connection, Service.BIND_AUTO_CREATE);
               //service.printHelloWorld();
             int x = service.getRandomNumber();
                Log.e("Start Bound Service", "Bound Successfuly and X value is ");
            }
        });

        btnStopService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                unbindService(connection);
                Log.e("Start Bound Service", "UnBounded Successfuly");
            }
        });

    }

    /** Defines callbacks for service binding, passed to bindService() */
    public ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            // We've bound to SmartyService, cast the IBinder and get SmartyService instance
            SmartyService.SmartyBinder smartyBinder = (SmartyService.SmartyBinder) service;
            MainActivity.this.service = smartyBinder.getService();
            mBound = true;
            Log.e(LOG_TAG, "onServiceConnected call");
        }

        @Override
        public void onServiceDisconnected(ComponentName className) {
            MainActivity.this.service = null;
            mBound = false;
            Log.e(LOG_TAG, "onServiceDisconnected call");
        }
    };
}



And this is my Service Code

package com.smarty_tech.boundservice;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import java.util.Random;

public class SmartyService extends Service {
    private static String LOG_TAG = "SmartyService";

    public SmartyService() {
    }

    // Binder given to clients
    private final IBinder binder = new SmartyBinder();
    // Random number generator
    private final Random mGenerator = new Random();

    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class SmartyBinder extends Binder{
        SmartyService getService(){
            // Return this instance of LocalService so clients can call public methods
            Log.v(LOG_TAG, "in SmartyBinder");
            return SmartyService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        //throw new UnsupportedOperationException("Not yet implemented");
       // printHelloWorld();
        Log.v(LOG_TAG, "in onBind");
        return binder;
    }

    @Override
    public void onRebind(Intent intent) {
        Log.v(LOG_TAG, "in onRebind");
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.v(LOG_TAG, "in onUnbind");
        return true;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(LOG_TAG, "onCreated Called !");
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(LOG_TAG, "onDestroy Called , I will miss you !");
    }

    /** method for clients */
    public void printHelloWorld(){
        //for(int i = 0; i < 1000 ; i++){
            Log.e(LOG_TAG, "Hello Wolrd");
        //}
    }

    /** method for clients */
    public int getRandomNumber() {
        return mGenerator.nextInt(100);
    }
    /*

    The SmartyBinder provides the getService() method for clients to retrieve the current instance of SmartyService.
    This allows clients to call public methods in the service. For example, clients can call printHelloWorld() from the service.
     */
}



and This is main_activity.xml of the layout

<pre><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_start_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Service"
        />

    <Button
        android:id="@+id/btn_stop_service"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop Service"
        />

</LinearLayout>



What I have tried:

When i try to start service, the following exception appears on Logcat

06-11 09:43:03.654 2380-2380/com.smarty_tech.boundservice E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.smarty_tech.boundservice, PID: 2380
    java.lang.NullPointerException
        at com.smarty_tech.boundservice.MainActivity$1.onClick(MainActivity.java:39)
        at android.view.View.performClick(View.java:4438)
        at android.view.View$PerformClick.run(View.java:18422)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5019)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        at dalvik.system.NativeStart.main(Native Method)

解决方案

1.onClick(MainActivity.java:39) at android.view.View.performClick(View.java:4438) at android.view.View


PerformClick.run(View.java:18422) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5019) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit


MethodAndArgsCaller.run(ZygoteInit.java:779) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) at dalvik.system.NativeStart.main(Native Method)


这篇关于为什么在启动绑定服务android时出现空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆