0
点赞
收藏
分享

微信扫一扫

Android为什么使用bindService

独西楼Q 2022-09-27 阅读 68


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)




举报

相关推荐

0 条评论