我尝试用活动和服务创建简单的通信。然后在从文档获得任何帮助后,我创建此服务以将数据从活动发送到服务并将数据从服务传递到活动。但是我得到了ResultReceiver的 我的活动: 我的服务(有错误): LogCat结果: 错误适用于此行:@Override
public void onCreate(Bundle savedInstanceState) {
resultReceiver = new MyResultReceiver(null);
txtview = (TextView) findViewById(R.id.txtview);
intent = new Intent(this, MyService.class);
intent.putExtra("receiver", resultReceiver);
startService(intent);
}
public class ToobaPayamakService extends Service{
private Timer timer = new Timer();
private MyTimerTask timerTask;
private ResultReceiver resultReceiver;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
resultReceiver = intent.getParcelableExtra("mLastID");
timerTask = new MyTimerTask();
timer.scheduleAtFixedRate(timerTask, 1000, 1000);
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
timer.cancel();
Bundle bundle = new Bundle();
bundle.putString("end", "Timer Stopped....");
resultReceiver.send(200, bundle);
}
class MyTimerTask extends TimerTask
{
public MyTimerTask() {
Bundle bundle = new Bundle();
bundle.putString("start", "Timer Started....");
resultReceiver.send(100, bundle);
}
@Override
public void run() {
SimpleDateFormat dateFormat = new SimpleDateFormat("s");
resultReceiver.send(Integer.parseInt(dateFormat.format(System.currentTimeMillis())), null);
}
}
}
Unable to start service com.sample.myService@41283e90 with Intent { cmp=com.sample/.myService(has extras) }: java.lang.NullPointerException
java.lang.RuntimeException: Unable to start service com.sample.myService@41283e90 with Intent { cmp=com.sample/.myService (has extras) }: java.lang.NullPointerException
resultReceiver.send(100, bundle);
答案 0 :(得分:1)
不确定这是否会成为问题但是:
intent.putExtra("receiver", resultReceiver);
--------
resultReceiver = intent.getParcelableExtra("mLastID");
您的识别字符串不匹配,这种方式永远不会有效。
希望有所帮助