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完成想要的任务。