Android實現–更改local後,啟動一個service

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.