您的位置:首页 > 移动开发 > Android开发

Android为什么使用bindService

2017-04-27 11:23 176 查看
public class MainActivity extends AppCompatActivity {

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

Intent intent = new Intent(this, TestService.class);
startService(intent);
}
//点击按钮 调用服务里面的方法
public void click(View v) {
//自己new 对象 脱离了谷歌框架 脱离了环境 没有上下文
TestService testService = new TestService();
testService.methodService();
}
}


public class TestService extends Service {
public TestService() {
}

@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
// throw new UnsupportedOperationException("Not yet implemented");
return null;
}
//在服务里面定义的方法
public void methodService() {
Toast.makeText(getApplicationContext(), "haha", Toast.LENGTH_SHORT).show();
}
}
点击按钮报错,

Caused by: java.lang.NullPointerException:
Attempt to invoke virtual method 'android.content.Context
android.content.Context.getApplicationContext()' on a null
object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:106)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: