ANDROID 使用 Service 在手机锁屏休眠状态下后台执行发送短信息回调HANDLE界面显示内容

MainActivity.java

public class MainActivity extends Activity implements  ServiceConnection {
    private TextView netStateText;
    private TextView sendedText;
    private TextView waitingText;
    private TextView lastFinishTimeText;
    SmsApplication app;
    boolean checkMoveTaskToBack = false;

    private PowerManager.WakeLock wakeLock = null;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try {
            setTitle(getString(R.string.app_name));
            setContentView(R.layout.activity_main);
            Bundle bundle = getIntent().getExtras();
            checkMoveTaskToBack = bundle.getBoolean("checkMoveTaskToBack");
            app = (SmsApplication) getApplication();
            int subscriptionId = bundle.getInt("subscriptionId");
            app.setSubscriptionId(subscriptionId);
            netStateText = (TextView) findViewById(R.id.netState);
            sendedText = (TextView) findViewById(R.id.sended);
            waitingText = (TextView) findViewById(R.id.waiting);
            lastFinishTimeText = (TextView) findViewById(R.id.lastFinishTime);
            if (checkMoveTaskToBack) {
                //  moveTaskToBack(true);
            }

            //绑定Service
            Intent intent = new Intent(MainActivity.this, MyService.class);
            bindService(intent, this, Service.BIND_AUTO_CREATE);
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, MyService.class.getName());
            wakeLock.acquire();


        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }



    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        MyService.Binder binder = (MyService.Binder) service;
        MyService myService = binder.getService();
        myService.setCallback(new MyService.Callback() {
            @Override
            public void onDataChange(Message msg) {
                handler.sendMessage(msg);
            }
        });
    }


    @Override
    public void onServiceDisconnected(ComponentName name) {

    }


    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            // 更新UI
            switch (msg.what) {
                case 1:
                    if (msg.getData() != null) {
                        netStateText.setText(msg.getData().getString("netStateText").toString());
                    } else {
                        netStateText.setText("数据错误!");
                    }
                    break;
                case 2:
                    if (msg.getData() != null) {
                        sendedText.setText("已发送:" + msg.getData().getInt("sended"));
                        waitingText.setText("待发送:" + msg.getData().getInt("waiting"));

                        if (msg.getData().getString("finishTime") != null) {
                            lastFinishTimeText.setText("最后发送时间:" + msg.getData().getString("finishTime"));
                        }
                    }
                    break;
            }

        }
    };

    @Override
    protected void onDestroy() {
        if (wakeLock != null) {
            wakeLock.release();
            wakeLock = null;
        }
        // TODO 自动生成的方法存根
        super.onDestroy();
        unbindService(this);
        app.getEngine().close();
    }


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.oraycn.es.androiddemo.MainActivity">


    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/netState"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="网络状态:" />

        <TextView
            android:id="@+id/sended"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="已发送:" />

        <TextView
            android:id="@+id/waiting"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="待发送:" />
        <TextView
            android:id="@+id/lastFinishTime"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="最后发送时间:" />
    </LinearLayout>

</LinearLayout>


MyService.java

public class MyService extends Service implements SMSResultListener {
    private Callback callback;

    SmsApplication app;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new Binder();
    }

    public class Binder extends android.os.Binder {
        public MyService getService() {
            return MyService.this;
        }
    }

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String TAG ="MyService";
    class UpdateNetState implements Runnable {
        @Override
        public void run() {
            android.os.Process
                    .setThreadPriority(Process.THREAD_PRIORITY_URGENT_DISPLAY);
            while (true) {
                try {
                    if (app.getEngine().connected()) {

                        Message msg = new Message();
                        msg.what = 1;
                        Bundle bundle = new Bundle();
                        bundle.putString("netStateText", "网络状态:正常");
                        Log.i(TAG,"网络状态:正常"+ System.currentTimeMillis());
                        msg.setData(bundle);
                        if (callback != null) {
                            callback.onDataChange(msg);
                        }
                    } else {
                        Message msg = new Message();
                        msg.what = 1;
                        Bundle bundle = new Bundle();
                        bundle.putString("netStateText", "网络状态:断开");
                        Log.i(TAG,"网络状态:断开"+ System.currentTimeMillis());
                        msg.setData(bundle);
                        if (callback != null) {
                            callback.onDataChange(msg);
                        }
                    }
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onSended(int sended, int waiting, Date finishTime) {
        try {
            Message msg = new Message();
            Bundle bundle = new Bundle();
            bundle.putInt("sended", sended);
            bundle.putInt("waiting", waiting);
            msg.what = 2;
            if (finishTime != null) {
                bundle.putString("finishTime", sdf.format(finishTime));
            }
            msg.setData(bundle);
            if (callback != null) {
                callback.onDataChange(msg);
            }
            // mActivityMessenger.send(msg);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    Thread updateNetState;

    @Override
    public void onCreate() {
        super.onCreate();
        app = (SmsApplication) getApplication();
        app.setSMSResultListener(this);
        updateNetState = new Thread(new UpdateNetState());
        updateNetState.start();
    }

    public void setCallback(Callback callback) {
        this.callback = callback;
    }

    public static interface Callback {
        void onDataChange(Message data);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}


SMSResultListener.java

public interface SMSResultListener {
    public void onSended(int sended, int waiting, Date finishTime);
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

悟V-SpHeNIC

支持科研技术

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值