1、定義一個類,繼承BroadcastReceiver,用於接收ACTION_LOCALE_CHANGED訊息,代碼如下:
package android.ipc;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class ipc extends BroadcastReceiver {
static final String ACTION = "android.intent.action.BOOT_COMPLETED";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().compareTo(Intent.ACTION_LOCALE_CHANGED) == 0)
{
//start activity
Intent smart_service = new Intent(Intent.ACTION_RUN);
smart_service.setClass(context, DateTimeService.class);
//smart_service.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(smart_service);
}
}
}
2、定義一個service,繼承Service,用於完成背景工作,代碼如下:
package android.ipc;
import android.content.Intent;
import android.app.Service;
import android.util.Log;
import android.widget.Toast;
import android.os.IBinder;
public class DateTimeService extends Service {
private final String TAG = "datetimeservice";
public IBinder onBind(Intent intent)
{
return null;
}
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
Toast.makeText(this, "start onstart", Toast.LENGTH_LONG).show();
Log.v(TAG, "start onstart");
// your task to add
stopService(intent);
}
public void onCreate()
{
super.onCreate();
Toast.makeText(this, "start oncreate", Toast.LENGTH_LONG).show();
Log.v(TAG, "start oncreate");
}
public void onDestroy()
{
super.onDestroy();
Toast.makeText(this, "start ondestroy", Toast.LENGTH_LONG).show();
Log.v(TAG, "start ondestroy");
}
}
3、在AndroidMenifese.xml中,註冊receiver,增加intent過濾,如下:
<receiver android:name="ipc">
<intent-filter>
<action android:name="android.intent.action.LOCALE_CHANGED" />
</intent-filter>
</receiver>
註冊service,如下:
<service android:name=".DateTimeService"></service>
這樣就可以在loval改變後,啟動service完成想要的任務。