我試圖讓我的服務在我的手機上有外撥電話時運行。但由於某種原因,我的服務在這種情況發生時無法運行。我知道「CallReceiver」的代碼會執行,因爲我使用了Toast消息來顯示它是否運行。我可以通過我的主要活動運行的服務,但這意味着無論撥出電話是否由它將運行....服務不從BroadcastReceiver運行? - Android
下面是我的代碼:
接收器:
package com.example.hiworld;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class CallReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, CallService.class));
Toast.makeText(context, "Call Receiver started",
Toast.LENGTH_LONG).show();
Log.d("Calling Someone", "onReceived");
}
}
的服務:
package com.example.hiworld;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.widget.Toast;
public class CallService extends IntentService {
public long StartTime=0;
public long EndTime =0;
public long TotalTime = 0;
public long NumFreeMins = 0;
public CallService() {
super("CallService");
}
@Override
protected void onHandleIntent(Intent intent) {
StartTime = (System.currentTimeMillis())/60;
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if(tm.getCallState()==0) //getting the time whenever the phone is off
{
EndTime = (System.currentTimeMillis())/60;
TotalTime = EndTime-StartTime;
NumFreeMins = 300-TotalTime;
//notify user
this.displaymsg();
}
}
public void displaymsg()
{
Toast toast = Toast.makeText(getApplicationContext(), ""+NumFreeMins, Toast.LENGTH_SHORT);
toast.show();
}
}
我見過一些人使用日e行:代替
context.startService(new Intent(this, CallService.class));
:
context.startService(new Intent(context, CallService.class));
,但後者沒有工作對我來說...
顯示您的日誌只是爲了瞭解啓動服務時是否有問題。我會將您的問題指向與標籤相關的清單中缺少的內容。 –
yugidroid
2012-07-10 23:52:34
查看本教程將幫助你[從廣播接收器開始服務](http://rdcworld-android.blogspot.in/2012/03/start-service-from-broadcast-receiver.html) – swiftBoy 2012-07-11 15:34:51