我想在我的拨号器(默认或股票拨号器)打开时启动服务。 我的服务只是祝酒消息。 如何启动拨号器服务。 startService命令在MainActivity工作,但在拨号器打开时它不起作用。
我的代码如下所示:
的Manifest.xml
package="com.example.chatheads">
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
android:name=".MyService"
android:enabled="true"
android:exported="true" />
MainActivity.java
package com.example.chatheads;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.method.DialerKeyListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button startService,stopService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService=(Button)findViewById(R.id.startService);
stopService=(Button)findViewById(R.id.stopService);
if(getIntent().getAction().equals(Intent.ACTION_DIAL)) {
Intent intent = new Intent(getBaseContext(), MyService.class);
startService(intent);
}
startService.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startService(new Intent(getApplication(), MyService.class));
}
});
stopService.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
stopService(new Intent(getApplication(), MyService.class));
}
});
}
}
Myservice.java
package com..service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
intent.getStringExtra("MY_MESSAGE");
//stopSelf();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
此代码无效。 在MainActivity中调用startService时启动的服务。 但是当拨号器打开它不起作用。