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)
相关文章推荐
- 为什么Android开发使用Java而不是C++?
- 关于android使用dexjar反编译后的classes.dex.dex2jar.jar为什么jd gui打不开?
- Android(java)学习笔记226:服务(service)之为什么使用服务
- Android library中为什么不能使用switch-case语句访问资源ID
- android 为什么不建议使用Thread.stop()
- Android学习札记13:为什么更推荐使用Parcelable来在Activity间传递数据,而不是Serializable?
- android 为什么尽量不使用enum
- 我为什么主张反对使用Android Fragment
- 为什么Android AsyncTask的使用要遵循五大原则
- Android为什么要设计出Bundle而不是直接使用HashMap来进行数据传递
- 为什么Android使用弱加密算法?
- 对于Android为什么要使用Handle sendMessage()
- android进程优先级&有了Thread为什么还要使用service
- Java4Android-为什么使用抽象类和抽象函数
- Android 为什么AlertDialog 里不能使用getapplicationcontext
- 为什么Android系统需要使用C、C++和Java语言共同开发
- android中为什么使用service?
- 为什么Android系统需要使用C、C++和Java语言共同开发
- Android 中 EventBus 的使用(1):为什么要使用 EventBus
- 我们为什么要在Android中使用RxJava