[英]How to launch the apk when there is change in phone state (broadcast receiver) that will start the service
我想創建不帶ui應用程序的應用程序,但要在更改手機狀態時啟動我的應用程序,這將啟動另一個執行任務代碼但無法正常工作的服務
public void onReceive(Context context, Intent intent)
{
Bundle bundle = intent.getExtras();
if (bundle == null)
return;
String phoneNumber = null;
// Incoming call
String state = bundle.getString(TelephonyManager.EXTRA_STATE);
if ((state != null)
&& (state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)))
{
phoneNumber = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
Intent i = new Intent(context,ServiceFromBr.class);
context.startService(i);
}
// Outgoing call
else if (state == null) {
phoneNumber = bundle.getString(Intent.EXTRA_PHONE_NUMBER);
Intent i = new Intent(context,ServiceFromBr.class);
context.startService(i);
}
}
服務代碼為:
public class ServiceFromBr extends Service
{
public void onCreate()
{
Toast t= Toast.makeText(getApplicationContext(), "in Service", Toast.LENGTH_LONG);
t.show();
}
}
<service android:name=".ServiceFromBr"></service>
<receiver android:name=".BroadcastStart"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
它用於廣播接收器而不是服務。
從您的啟動其他應用程序:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setComponent(new ComponentName(packageName,mainActivity));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
您可以像這樣獲得主要活動:
Intent mIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
if (mIntent != null) {
if (mIntent.getComponent() != null) {
mainActivity = mIntent.getComponent().getClassName();
}
}
並且您必須在清單文件中添加主要活動。
您的代碼看起來像下面的代碼。
String mainActivity;
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (intent.getAction().equals("android.intent.action.PHONE_STATE")) {
String state = intent.getExtras().getString(
TelephonyManager.EXTRA_STATE);
if ((state != null)
&& (state.equals(TelephonyManager.EXTRA_STATE_RINGING))) {
CallLogReceiver.phoneNo = intent.getExtras().getString(
"incoming_number");
Intent mIntent = context.getPackageManager()
.getLaunchIntentForPackage("com.example.calculator"); //here i take example of calculator demo
if (mIntent != null) {
if (mIntent.getComponent() != null) {
mainActivity = mIntent.getComponent().getClassName();
}
}
Intent launchIntent = new Intent(Intent.ACTION_MAIN);
launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
launchIntent.setComponent(new ComponentName(
"com.example.calculator", mainActivity));
launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(launchIntent);
//further logic of your code
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.