我要求在Android中创建服务并使服务从MainActivity
开始睡眠10分钟。
如何通过活动让服务入睡?
MyService.java
public class MyService extends IntentService {
public MyService() {
super("MyService");
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
protected void onHandleIntent(Intent intent) {
// Extract the receiver passed into the service
ResultReceiver rec = intent.getParcelableExtra("receiver");
// Extract additional values from the bundle
String msg = intent.getStringExtra("msg");
// To send a message to the Activity, create a pass a Bundle
Bundle bundle = new Bundle();
bundle.putString("res", msg);
// Here we call send passing a resultCode and the bundle of extras
rec.send(Activity.RESULT_OK, bundle);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button serviceTriggerBtn;
public MyReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serviceTriggerBtn = (Button) findViewById(R.id.serviceTriggerBtn);
serviceTriggerBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, MyService.class);
i.putExtra("msg", "ACTIVITY DATA");
startService(i);
}
});
}
// Setup the callback for when data is received from the service
public void setupServiceReceiver() {
receiver = new MyReceiver(new Handler());
// This is where we specify what happens when data is received from the service
receiver.setReceiver(new MyReceiver.Receiver() {
@Override
public void onReceiveResult(int resultCode, Bundle resultData) {
if (resultCode == RESULT_OK) {
String resultValue = resultData.getString("msg");
Toast.makeText(MainActivity.this, resultValue, Toast.LENGTH_SHORT).show();
}
}
});
}
}
我在清单文件中注册了服务,服务正在正确调用。但我坚持要让服务入睡。请帮帮我。