Toast in a self running service

末鹿安然 提交于 2019-12-30 14:07:13

问题


I have an android activity which runs a remote service and then quits. The service itself, polls on a device node, and checks for changes, I want to use toast to alert the user, but I didn't mange to get it to work. the Toast is not showing, and after a while, Android shouts that my app is not responding. BTW, I don't want to start the activity again and display the toast from there, I just want it to pop on the current screen shown to the user.

Here is the service code:

public class MainService extends Service {

    // Native methods
    public native static int GetWiegandCode();
    public native static void openWiegand();
    public native static void closeWiegand();

    static int code = 0;

    // Other
    private static final String TAG = MainService.class.getSimpleName();
    private Handler handler;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void run() {
        Handler h;
        while (true) {
            code = GetWiegandCode();
            if (code > 0) {
                h = new Handler(this.getMainLooper());
                h.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getBaseContext(),
                            "ID " + Integer.toString(code) +
                            "Just entered", Toast.LENGTH_LONG).show();
                    }
                });
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        openWiegand();
        Log.i(TAG, "Service Starting");
        this.run();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        closeWiegand();
        Log.i(TAG, "Service destroying");
    }

    static {
        System.loadLibrary("wiegand-toast");
    }
}

回答1:


You can't call a Toast message from the Service. You can't do anything with the UI except from the UI thread. You're going to need to research one of the many ways to communicate with your UI thread from your service - BroadcastReciever, Messenger, AIDL, etc.

For what you're trying to do, you probably don't need to go as far as the AIDL route. Check out this example the Messenger implementation and then check out the complete example from the sdk-samples:

http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/MessengerService.html



来源:https://stackoverflow.com/questions/7298083/toast-in-a-self-running-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!