Android的服务启动活动不一样的反应,我认为它应该 [英] android service to start activity not reacting like I think it should

查看:162
本文介绍了Android的服务启动活动不一样的反应,我认为它应该的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直工作在监听蓝牙消息,我的手机上启动应用程序的各种程序。每个下面的工作正常,如果显示主布局,但一旦命令之一被称为其他不正常的反应。这里是code两个命令:

 如果(readMessage.equals(按钮))
{
    意图I =新意图(Intent.ACTION_MAIN);
    软件包管理系统经理= getPackageManager();
    I = manager.getLaunchIntentForPackage(com.google.android.apps.maps);
    Log.d(主,我是:+ I);
    i.addCategory(Intent.CATEGORY_LAUNCHER);
    startActivity(ⅰ);
    Log.d(主,地图推);
}
如果(readMessage.equals(家))
{
    意图startMain =新意图(Intent.ACTION_MAIN);
    startMain.addCategory(Intent.CATEGORY_HOME);
    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(startMain);
    Log.d(主,主页推送);
}

因此​​,例如消息家里发送,应用程序将显示主屏幕。但是,如果显示后,主屏幕和消息按钮被送到什么也没有发生,但我知道,code从日志调用。

我需要把我的消息处理程序到它自己的服务?

下面是两个java文件:

主营:

 包com.lorenjz.phoneremotefive;进口java.lang.Thread.State中;
进口的java.util.ArrayList;
进口java.util.Set中;进口android.os.Bundle;
进口android.os.Handler;
进口android.os.Message;
进口android.app.Activity;
进口android.bluetooth.BluetoothAdapter;
进口android.bluetooth.BluetoothDevice;
进口android.content.ComponentName;
进口android.content.Intent;
进口android.content.Shared preferences;
进口android.content.Shared preferences.OnShared preferenceChangeListener;
进口android.content.pm.PackageManager;
进口android.util.Log;
进口android.view.Menu;
进口android.view.MenuInflater;
进口android.view.MenuItem;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.AdapterView;
进口android.widget.Button;
进口android.widget.ListView;
进口android.widget.TextView;
进口android.widget.Toast;
。进口的Andr​​oid preference preferenceActivity;
。进口的Andr​​oid preference preferenceManager。公共类MainRemote延伸活动{    私有静态的TextView btstatus = NULL;
    私人按钮closeButt;
    私人TextView的铃声= NULL;
    私人TextView的checkbox2 = NULL;
    私人布尔serverState = FALSE;    // declerations:    私人BluetoothAdapter btAdapter;    公众的ArrayList myArray的;
    公众的ArrayList devArray;    私人诠释myContext;
    私人BlueStuff mChatService = NULL;    //从BluetoothChatService处理程序中发送消息类型
    公共静态最终诠释MESSAGE_STATE_CHANGE = 1;
    公共静态最终诠释MESSAGE_READ = 2;
    公共静态最终诠释MESSAGE_WRITE = 3;
    公共静态最终诠释MESSAGE_DEVICE_NAME = 4;
    公共静态最终诠释MESSAGE_TOAST = 5;    公共静态最后弦乐DEVICE_NAME =DEVICE_NAME;    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main_remote);        btstatus =(的TextView)findViewById(R.id.btstatus);
        closeButt =(按钮)findViewById(R.id.close);
        /**checkbox=(TextView)findViewById(R.id.checkbox);
        checkbox2 =(的TextView)findViewById(R.id.checkbox2)** /        共享preferences preFS = preferenceManager
                .getDefaultShared preferences(本);
        //checkbox.setText(new布尔(prefs.getBoolean(复选框,FALSE))
            //的ToString());
        布尔servState =(新布尔(prefs.getBoolean(serverstate,FALSE))的booleanValue());
        如果(servState =真){
            Log.d(主,它认为服务器应该是);
            //checkbox2.setText(new布尔(prefs.getBoolean(checkbox2,FALSE))
                //的ToString());
            mChatService =新BlueStuff(getBaseContext(),mHandler);
            INT stateString = mChatService.getState();
            Log.d(主,聊天服务+ stateString);
            // + mChatService.getState()
            mChatService.start();
        }
        INT stateString = mChatService.getState();
        Log.d(主,事情发生后聊天服务:+ stateString);
        btstatus.setText(暂时还没有连接);
        setupUI();        closeButt.setOnClickListener(新OnClickListener(){
            公共无效的onClick(视图v){                mChatService.stop();
            }
        });
    }    @覆盖
    公共无效onResume(){
        super.onResume();        共享preferences preFS = preferenceManager
                .getDefaultShared preferences(本);
        //checkbox.setText(new布尔(prefs.getBoolean(复选框,FALSE))
            //的ToString());
        字符串servState =(新布尔(prefs.getBoolean(serverstate,FALSE))的toString());
        Log.d(主,服务器状态:+ servState);
        //checkbox2.setText(new布尔(prefs.getBoolean(checkbox2,FALSE))
            //的ToString());           //执行此检查在onResume()覆盖,其中BT是事实
        //调用onStart()中没有启用,所以我们停下来启用它...
        // onResume()将会被调用时ACTION_REQUEST_ENABLE活动的回报。
        如果(mChatService!= NULL){
            //只有当状态STATE_NONE,难道我们知道,我们尚未启动
            如果(mChatService.getState()== BlueStuff.STATE_NONE){
              //启动蓝牙聊天服务
              mChatService.start();
              startService(新意图(这一点,BlueStuff.class));            }
        }
    }    @覆盖
    公共布尔onCreateOptionsMenu(菜单菜单){
        MenuInflater吹气= getMenuInflater();
        inflater.inflate(R.menu.activity_main_remote,菜单);
        返回true;
    }    @覆盖
    公共布尔onOptionsItemSelected(菜单项项){
        开关(item.getItemId()){
            案例R.id.menu_settings:
            startActivity(新意图(这一点,preferencesB.class));
            返回true;
        }        回报(super.onOptionsItemSelected(项目));
    }
     公共无效setupUI(){
    }    私人最终处理程序mHandler =新的处理程序(){
        @覆盖
        公共无效的handleMessage(消息MSG){
            开关(msg.what){
                案例MESSAGE_STATE_CHANGE:
                    //如果(D)Log.i(主,MESSAGE_STATE_CHANGE:+ msg.arg1);
                    开关(msg.arg1){
                        案例BlueStuff.STATE_CONNECTED:
                            Toast.makeText(getApplicationContext(),连接,Toast.LENGTH_SHORT).show();
                            //setStatus(getString(R.string.title_connected_to,mConnectedDeviceName));
                            //mConversationArrayAdapter.clear();
                            打破;
                        案例BlueStuff.STATE_CONNECTING:
                            Toast.makeText(getApplicationContext(),连接,Toast.LENGTH_SHORT).show();
                            //setStatus(R.string.title_connecting);
                            打破;
                        案例BlueStuff.STATE_LISTEN:
                            Toast.makeText(getApplicationContext(),听,Toast.LENGTH_SHORT).show();
                            打破;
                        案例BlueStuff.STATE_NONE:
                            //setStatus(R.string.title_not_connected);
                            打破;
                    }
                    打破;
                / **情况下MESSAGE_WRITE:
                    字节[] = writeBuf(字节[])msg.obj;
                    //构建从缓冲区中的字符串
                    字符串的WriteMessage =新的String(writeBuf);
                    mConversationArrayAdapter.add(我:+的WriteMessage);
                    打破;**/
                案例MESSAGE_READ:
                    字节[] =的ReadBuf(字节[])msg.obj;
                    //从缓冲区中的有效字节构造字符串
                    字符串readMessage =新的String(的ReadBuf,0,msg.arg1);
                    //mConversationArrayAdapter.add(mConnectedDeviceName+:+ readMessage);
                    //Toast.makeText(getApplicationContext(),信息:+ readMessage,Toast.LENGTH_SHORT).show();
                    如果(readMessage.equals(按钮))
                    {
                        / **意图startMain =新意图(Intent.ACTION_MAIN);
                        startMain.addCategory(Intent.CATEGORY_HOME);
                        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(startMain)** /                        意图I =新意图(Intent.ACTION_MAIN);
                        软件包管理系统经理= getPackageManager();
                        I = manager.getLaunchIntentForPackage(com.google.android.apps.maps);
                        Log.d(主,我是:+ I);
                        i.addCategory(Intent.CATEGORY_LAUNCHER);
                        startActivity(ⅰ);
                        Log.d(主,地图推);                        / **意图launch_intent =新意图(android.intent.action.MAIN);
                        launch_intent.addCategory(android.intent.category.LAUNCHER);
                        launch_intent.setComponent(新单元名(com.google.android.maps,地图));
                        launch_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);                        startActivity(launch_intent)** /
                    }
                    如果(readMessage.equals(家))
                    {
                        意图startMain =新意图(Intent.ACTION_MAIN);
                        startMain.addCategory(Intent.CATEGORY_HOME);
                        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(startMain);
                        Log.d(主,主页推送);
                    }
                    打破;
                / **情况下MESSAGE_DEVICE_NAME:
                    //保存所连接的设备的名称
                    。mConnectedDeviceName = msg.getData()的getString(设备);
                    Toast.makeText(getApplicationContext(),连接到
                                   + mConnectedDeviceName,Toast.LENGTH_SHORT).show();
                    打破;
                案例MESSAGE_TOAST:
                    Toast.makeText(getApplicationContext(),msg.getData()的getString(TOAST)
                                   Toast.LENGTH_SHORT).show();
                    打破;**/
            }
        }
    };    最终静态无效updateBTStatus(INT mState){
        Log.d(主,更新名为mState是:+ mState);
        btstatus.setText(切换之前);
        statusTry();        开关(mState){
            情况1:
                btstatus.setText(监听连接);
                Log.d(主,状态应该被监听连接);
            案例2:
                btstatus.setText(连接);
            案例3:
                btstatus.setText(已连接);
        }    }    公共静态无效statusTry(){
        btstatus.setText(后开关试);
    }
}

蓝色的东西:

 包com.lorenjz.phoneremotefive;进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.OutputStream中;
进口java.util.UUID中;进口android.app.Service;
进口android.bluetooth.BluetoothAdapter;
进口android.bluetooth.BluetoothDevice;
进口android.bluetooth.BluetoothServerSocket;
进口android.bluetooth.BluetoothSocket;
进口android.content.Context;
进口android.content.Intent;
进口android.os.Bundle;
进口android.os.Handler;
进口android.os.IBinder;
进口android.os.Message;
进口android.util.Log;
进口android.widget.Toast;公共类BlueStuff延伸服务{    私有静态最后弦乐TAG =蓝;    私有静态最终布尔D =真实的;    私人最终UUID MY_UUID = UUID.fromString(00001101-0000-1000-8000-00805F9B34FB);
    私人最终字符串名称=齐默;
    //私人BluetoothAdapter mBluetoothAdapter;    私人最终BluetoothAdapter mAdapter;
    私人最终处理程序mHandler;
    私人诠释mState;    公共静态最终诠释STATE_NONE = 0; //我们什么都不做
    公共静态最终诠释STATE_LISTEN = 1; //现在侦听传入连接
    公共静态最终诠释STATE_CONNECTING = 2; //现在启动的出站连接
    公共静态最终诠释STATE_CONNECTED = 3; //现在连接到远程设备    私人ConnectThread mConnectThread;
    私人ConnectedThread mConnectedThread;
    私人AcceptThread mSecureAcceptThread;
    私人AcceptThread mInsecureAcceptThread;    / **
     *构造函数。 prepares新BluetoothChat会话。
     * @参数上下文中的UI活动上下文
     * @参数处理程序处理程序将消息发送回UI活动
     * /
    公共BlueStuff(上下文的背景下,处理程序处理){
        mAdapter = BluetoothAdapter.getDefaultAdapter();
        mState = STATE_NONE;
        mHandler =处理程序;
    }    / **
     *返回当前连接状态。 * /
    公共同步INT的getState(){
        返回mState;
    }    / **
     *启动聊天服务。具体来说开始AcceptThread,开始了
     *会话听力(服务器)模式。由活动onResume()调用* /
    公共同步启动无效(){
        如果(D)Log.d(TAG,开始);        //取消任何线程试图建立连接
        如果(!mConnectThread = NULL){mConnectThread.cancel(); mConnectThread = NULL;}        //取消任何线程当前正在运行的连接
        如果(!mConnectedThread = NULL){mConnectedThread.cancel(); mConnectedThread = NULL;}        的setState(STATE_LISTEN);
        如果(mInsecureAcceptThread == NULL){
            mInsecureAcceptThread =新AcceptThread();
            mInsecureAcceptThread.start();
        }
    }    公共无效停止(){
        mConnectedThread.cancel();
    }    / **
     *设置聊天连接的当前状态
     * @参数状态的整数定义当前连接状态
     * /
    私人同步无效的setState(INT状态){
        如果(D)Log.d(TAG的setState()+ mState + - >中+状态);
            mState =状态;        //给这个新状态的处理程序,以便在UI活动可以更新
        mHandler.obtainMessage(MainRemote.MESSAGE_STATE_CHANGE,州,-1).sendToTarget();
    }    类AcceptThread继承Thread {
        私人最终BluetoothServerSocket mmServerSocket;        公共AcceptThread(){            //使用了以后分配给mmServerSocket一个临时对象,
            //因为mmServerSocket是最后
            BluetoothServerSocket TMP = NULL;
            尝试{
                // MY_UUID是应用程序的UUID字符串,还用于客户端code                // TMP = mAdapter.listenUsingRfcommWithServiceRecord(姓名,MY_UUID);
                TMP = mAdapter.listenUsingRfcommWithServiceRecord(姓名,MY_UUID);
            }赶上(IOException异常五){}
            Log.d(蓝,听着失败TMP 1C:+ TMP);            mmServerSocket = tmp目录;
            Log.d(蓝,mmServerSocket 1:+ mmServerSocket);
            MainRemote.updateBTStatus(mState);
        }        公共无效的run(){
            Log.d(蓝,运行名为);
            的BluetoothSocket插座= NULL;
            //请听,直到发生异常或者会返回一个socket
            而(真){
                尝试{
                    Log.d(蓝,mmServerSocket 2:+ mmServerSocket);
                    插座= mmServerSocket.accept();
                }
                赶上(IOException异常五){
                    打破;
                }
                //如果连接被接受
                / **如果(插座!= NULL){
                    //做工作,以管理(在一个单独的线程)的连接
                    // manageConnectedSocket(插座);
                    //mmServerSocket.close();
                    Log.d(蓝,连接被接受);
                    MainRemote.updateBTStatus(mState);
                    打破;
                } ** /
                如果(插座!= NULL){
                    同步(BlueStuff.this){
                        开关(mState){
                            案例STATE_LISTEN:
                            案例STATE_CONNECTING:
                                //状况正常。启动连接线。
                                连接(插座,socket.getRemoteDevice());
                                打破;
                            案例STATE_NONE:
                            案例STATE_CONNECTED:
                                //要么没有准备或已连接。终止新的套接字。
                                尝试{
                                    socket.close();
                                }赶上(IOException异常五){
                                    Log.e(TAG,无法关闭不必要的插座,E);
                                }
                                打破;
                        }
                    }
                }
            }
        }        / **将取消监听套接字,并导致线程结束* /
        公共无效取消(){
            尝试{
                mmServerSocket.close();
            }赶上(IOException异常五){}
        }
    }    类ConnectThread继承Thread {
        最终的BluetoothSocket mmSocket;
        私人最终BluetoothDevice类mmDevice;        公共ConnectThread(BluetoothDevice类设备){
            //使用了以后分配给mmSocket一个临时对象,
            //因为mmSocket是最后
            TMP的BluetoothSocket = NULL;
            mmDevice =设备;            //获取的BluetoothSocket与给定的BluetoothDevice类连接
            尝试{
                // MY_UUID是应用程序的UUID字符串,也使用由服务器code
                TMP = device.createRfcommSocketToServiceRecord(MY_UUID);
            }赶上(IOException异常五){}
            mmSocket = tmp目录;
        }        公共无效的run(){
            //取消的发现,因为它会在连接减慢
            mAdapter.cancelDiscovery();            尝试{
                //设备通过套接字连接。这将阻止
                //直到成功或者抛出一个异常
                mmSocket.connect();
            }赶上(IOException异常的ConnectException){
                // 无法连接;关闭套接字,走出
                尝试{
                    mmSocket.close();
                }赶上(IOException异常closeException){}
                返回;
            }            //做工作,以管理(在一个单独的线程)的连接
            // manageConnectedSocket(mmSocket);
        }        / **将取消正在进行中的连接,并关闭套接字* /
        公共无效取消(){
            尝试{
                mmSocket.close();
            }赶上(IOException异常五){}
        }
    }    类ConnectedThread继承Thread {
        私人最终的BluetoothSocket mmSocket;
        私人最终的InputStream mmInStream;
        私人最终的OutputStream mmOutStream;        公共ConnectedThread(插座的BluetoothSocket){
            mmSocket =插座;
            InputStream的tmpIn = NULL;
            OutputStream的tmpOut = NULL;            //获取输入和输出流,使用临时对象,因为
            //成员流是决赛
            尝试{
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            }赶上(IOException异常五){}            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }        公共无效的run(){
            字节[]缓冲区=新的字节[1024]; //缓冲存储区的流
            诠释字节; //个字节read()返回            //继续听InputStream的,直到出现异常
            而(真){
                尝试{
                    //从InputStream读
                    字节= mmInStream.read(缓冲);
                    //发送所获得的字节到UI活动
                    mHandler.obtainMessage(MainRemote.MESSAGE_READ,字节,-1​​,缓冲液)
                            .sendToTarget();
                    Log.d(蓝,消息收到!:+字节);
                }赶上(IOException异常五){
                    打破;
                }
            }
        }        / *从主活动调用此将数据发送到所述远程装置* /
        公共无效写入(字节[]字节){
            尝试{
                mmOutStream.write(字节);
            }赶上(IOException异常五){}
        }        / *从主要活动调用此来关闭连接* /
        公共无效取消(){
            尝试{
                mmSocket.close();
            }赶上(IOException异常五){}
        }
    }
    / **
     *启动ConnectedThread开始管理蓝牙连接
     * @参数插座在其上进行连接的BluetoothSocket的
     * @参数设备已连接该BluetoothDevice类
     * /
    公共同步无效连接(的BluetoothSocket插座,BluetoothDevice类
            设备){
        //如果(D)Log.d(TAG,连接器,插座类型:+ socketType);        //取消已完成的连接线
        如果(!mConnectThread = NULL){mConnectThread.cancel(); mConnectThread = NULL;}        //取消任何线程当前正在运行的连接
        如果(!mConnectedThread = NULL){mConnectedThread.cancel(); mConnectedThread = NULL;}        //取消接受线程,因为我们只需要连接到一台设备
        如果(mSecureAcceptThread!= NULL){
            mSecureAcceptThread.cancel();
            mSecureAcceptThread = NULL;
        }
        如果(mInsecureAcceptThread!= NULL){
            mInsecureAcceptThread.cancel();
            mInsecureAcceptThread = NULL;
        }        //开始线程管理连接并执行传输
        mConnectedThread =新ConnectedThread(插座);
        mConnectedThread.start();        //发送连接设备的名称回UI活动
        消息味精= mHandler.obtainMessage(MainRemote.MESSAGE_DEVICE_NAME);
        束束=新包();
        bundle.putString(MainRemote.DEVICE_NAME,device.getName());
        msg.setData(包);
        mHandler.sendMessage(MSG);        的setState(STATE_CONNECTED);
    }    @覆盖
    公众的IBinder onBind(意向意图){
        // TODO自动生成方法存根
        返回null;
    }
}


解决方案

它不是什么也没有发生。它的活动是不重新创建。尝试覆盖在onStart()我敢打赌,这是越来越称为替代。

I've been working on a program that listens for bluetooth messages to start various apps on my phone. Each of the following work correctly if the main layout is displayed but once one of the commands is called the other does not react properly. Here is the code for the two commands:

if (readMessage.equals("Button"))
{
    Intent i = new Intent(Intent.ACTION_MAIN);
    PackageManager manager = getPackageManager();
    i = manager.getLaunchIntentForPackage("com.google.android.apps.maps");
    Log.d("Main","i is:  "+ i);
    i.addCategory(Intent.CATEGORY_LAUNCHER);
    startActivity(i);
    Log.d("Main","Map pushed");
}
if (readMessage.equals("Home"))
{
    Intent startMain = new Intent(Intent.ACTION_MAIN);
    startMain.addCategory(Intent.CATEGORY_HOME);
    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(startMain);
    Log.d("Main","Home pushed");
} 

So for example the message home is sent, the app will display the home screen. However if after the home screen is displayed and the message "Button" is sent nothing happens, but I know that the code is called from the Log.

Do I need to put my message handler into it's own service?

Here are the two java files:

Main:

package com.lorenjz.phoneremotefive;

import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.Set;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;

public class MainRemote extends Activity {

    private static TextView btstatus=null;
    private Button closeButt;
    private TextView ringtone=null;
    private TextView checkbox2=null;
    private Boolean serverState = false;

    //declerations:

    private BluetoothAdapter btAdapter;

    public ArrayList myArray;
    public ArrayList devArray;



    private int myContext;
    private BlueStuff mChatService = null;

    // Message types sent from the BluetoothChatService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;

    public static final String DEVICE_NAME = "device_name";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_remote);

        btstatus=(TextView)findViewById(R.id.btstatus);
        closeButt=(Button)findViewById(R.id.close);
        /**checkbox=(TextView)findViewById(R.id.checkbox);
        checkbox2=(TextView)findViewById(R.id.checkbox2);**/

        SharedPreferences prefs=PreferenceManager
                .getDefaultSharedPreferences(this);
        //checkbox.setText(new Boolean(prefs.getBoolean("checkbox", false))
            //    .toString());
        Boolean servState = (new Boolean(prefs.getBoolean("serverstate", false)).booleanValue());
        if (servState = true){
            Log.d("Main","It thinks the server should be on");
            //checkbox2.setText(new Boolean(prefs.getBoolean("checkbox2", false))
                //    .toString());
            mChatService = new BlueStuff(getBaseContext(), mHandler);
            int stateString = mChatService.getState();
            Log.d("Main","chat service:  " + stateString);
            //+ mChatService.getState()
            mChatService.start();
        }
        int stateString = mChatService.getState();
        Log.d("Main","After stuff happens. chat service:  " + stateString);
        btstatus.setText("No Connection yet");
        setupUI();

        closeButt.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {

                mChatService.stop();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();

        SharedPreferences prefs=PreferenceManager
                .getDefaultSharedPreferences(this);
        //checkbox.setText(new Boolean(prefs.getBoolean("checkbox", false))
            //    .toString());
        String servState = (new Boolean(prefs.getBoolean("serverstate", false)).toString());
        Log.d("Main","Server State:  " +servState);
        //checkbox2.setText(new Boolean(prefs.getBoolean("checkbox2", false))
            //    .toString());

           // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
        if (mChatService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (mChatService.getState() == BlueStuff.STATE_NONE) {
              // Start the Bluetooth chat services
              mChatService.start();
              startService(new Intent(this, BlueStuff.class));

            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.activity_main_remote, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {       
            case R.id.menu_settings:
            startActivity(new Intent(this, PreferencesB.class));        
            return true;      
        }  

        return(super.onOptionsItemSelected(item));
    }


     public void setupUI(){


    }

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_STATE_CHANGE:
                    //if(D) Log.i("Main", "MESSAGE_STATE_CHANGE: " + msg.arg1);
                    switch (msg.arg1) {
                        case BlueStuff.STATE_CONNECTED:
                            Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show();
                            //setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
                            //mConversationArrayAdapter.clear();
                            break;
                        case BlueStuff.STATE_CONNECTING:
                            Toast.makeText(getApplicationContext(), "Connecting", Toast.LENGTH_SHORT).show();
                            //setStatus(R.string.title_connecting);
                            break;
                        case BlueStuff.STATE_LISTEN:
                            Toast.makeText(getApplicationContext(), "Listening", Toast.LENGTH_SHORT).show();
                            break;
                        case BlueStuff.STATE_NONE:
                            //setStatus(R.string.title_not_connected);
                            break;
                    }
                    break;
                /**case MESSAGE_WRITE:
                    byte[] writeBuf = (byte[]) msg.obj;
                    // construct a string from the buffer
                    String writeMessage = new String(writeBuf);
                    mConversationArrayAdapter.add("Me:  " + writeMessage);
                    break;**/
                case MESSAGE_READ:
                    byte[] readBuf = (byte[]) msg.obj;
                    // construct a string from the valid bytes in the buffer
                    String readMessage = new String(readBuf, 0, msg.arg1);
                    //mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);
                    //Toast.makeText(getApplicationContext(), "Message:  " + readMessage, Toast.LENGTH_SHORT).show();
                    if (readMessage.equals("Button"))
                    {
                        /**Intent startMain = new Intent(Intent.ACTION_MAIN);
                        startMain.addCategory(Intent.CATEGORY_HOME);
                        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(startMain);**/

                        Intent i = new Intent(Intent.ACTION_MAIN);
                        PackageManager manager = getPackageManager();
                        i = manager.getLaunchIntentForPackage("com.google.android.apps.maps");
                        Log.d("Main","i is:  "+ i);
                        i.addCategory(Intent.CATEGORY_LAUNCHER);
                        startActivity(i);
                        Log.d("Main","Map pushed");

                        /**Intent launch_intent = new Intent("android.intent.action.MAIN");
                        launch_intent.addCategory("android.intent.category.LAUNCHER");
                        launch_intent.setComponent(new ComponentName("com.google.android.maps", "map"));
                        launch_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                        startActivity(launch_intent);**/
                    }
                    if (readMessage.equals("Home"))
                    {
                        Intent startMain = new Intent(Intent.ACTION_MAIN);
                        startMain.addCategory(Intent.CATEGORY_HOME);
                        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(startMain);
                        Log.d("Main","Home pushed");
                    }
                    break;
                /**case MESSAGE_DEVICE_NAME:
                    // save the connected device's name
                    mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                    Toast.makeText(getApplicationContext(), "Connected to "
                                   + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                    break;
                case MESSAGE_TOAST:
                    Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                                   Toast.LENGTH_SHORT).show();
                    break;**/
            }
        }
    };

    final static void updateBTStatus(int mState){
        Log.d("Main", "update called.  mState is:  " + mState);
        btstatus.setText("prior to switch");
        statusTry();

        switch(mState){
            case 1:
                btstatus.setText("Listening for connection");
                Log.d("Main","Status should be listening for connection");
            case 2:
                btstatus.setText("Connecting");
            case 3:
                btstatus.setText("Connected");
        }

    }

    public static void statusTry(){
        btstatus.setText("post switch try");
    }
}

Blue Stuff:

package com.lorenjz.phoneremotefive;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class BlueStuff extends Service{

    private static final String TAG = "Blue";

    private static final boolean D = true;

    private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private final String NAME = "Zimmer";
    //private BluetoothAdapter mBluetoothAdapter;

    private final BluetoothAdapter mAdapter;
    private final Handler mHandler;
    private int mState;

    public static final int STATE_NONE = 0;       // we're doing nothing
    public static final int STATE_LISTEN = 1;     // now listening for incoming connections
    public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
    public static final int STATE_CONNECTED = 3;  // now connected to a remote device

    private ConnectThread mConnectThread;
    private ConnectedThread mConnectedThread;
    private AcceptThread mSecureAcceptThread;
    private AcceptThread mInsecureAcceptThread;

    /**
     * Constructor. Prepares a new BluetoothChat session.
     * @param context  The UI Activity Context
     * @param handler  A Handler to send messages back to the UI Activity
     */
    public BlueStuff(Context context, Handler handler) {
        mAdapter = BluetoothAdapter.getDefaultAdapter();
        mState = STATE_NONE;
        mHandler = handler;
    }

    /**
     * Return the current connection state. */
    public synchronized int getState() {
        return mState;
    }

    /**
     * Start the chat service. Specifically start AcceptThread to begin a
     * session in listening (server) mode. Called by the Activity onResume() */
    public synchronized void start() {
        if (D) Log.d(TAG, "start");

        // Cancel any thread attempting to make a connection
        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

        setState(STATE_LISTEN);


        if (mInsecureAcceptThread == null) {
            mInsecureAcceptThread = new AcceptThread();
            mInsecureAcceptThread.start();
        }
    }

    public void stop(){
        mConnectedThread.cancel();
    }

    /**
     * Set the current state of the chat connection
     * @param state  An integer defining the current connection state
     */
    private synchronized void setState(int state) {
        if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
            mState = state;

        // Give the new state to the Handler so the UI Activity can update
        mHandler.obtainMessage(MainRemote.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
    }

    class AcceptThread extends Thread {
        private final BluetoothServerSocket mmServerSocket;

        public AcceptThread() {

            // Use a temporary object that is later assigned to mmServerSocket,
            // because mmServerSocket is final
            BluetoothServerSocket tmp = null;
            try {
                // MY_UUID is the app's UUID string, also used by the client code

                //tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
                tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
            } catch (IOException e) { }
            Log.d("Blue","Listen Failed tmp 1c:  " + tmp);

            mmServerSocket = tmp;
            Log.d("Blue","mmServerSocket 1:  " + mmServerSocket);
            MainRemote.updateBTStatus(mState);
        }

        public void run() {
            Log.d("Blue","Run Called");
            BluetoothSocket socket = null;
            // Keep listening until exception occurs or a socket is returned
            while (true) {
                try {
                    Log.d("Blue","mmServerSocket 2:  " + mmServerSocket);
                    socket = mmServerSocket.accept();
                }
                catch (IOException e) {
                    break;
                }
                // If a connection was accepted
                /** if (socket != null) {
                    // Do work to manage the connection (in a separate thread)
                    //manageConnectedSocket(socket);
                    //mmServerSocket.close();
                    Log.d("Blue","Connection was accepted");
                    MainRemote.updateBTStatus(mState);
                    break;
                }**/
                if (socket != null) {
                    synchronized (BlueStuff.this) {
                        switch (mState) {
                            case STATE_LISTEN:
                            case STATE_CONNECTING:
                                // Situation normal. Start the connected thread.
                                connected(socket, socket.getRemoteDevice());
                                break;
                            case STATE_NONE:
                            case STATE_CONNECTED:
                                // Either not ready or already connected. Terminate new socket.
                                try {
                                    socket.close();
                                } catch (IOException e) {
                                    Log.e(TAG, "Could not close unwanted socket", e);
                                }
                                break;
                        }
                    }
                }
            }
        }

        /** Will cancel the listening socket, and cause the thread to finish */
        public void cancel() {
            try {
                mmServerSocket.close();
            } catch (IOException e) { }
        }
    }

    class ConnectThread extends Thread {
        final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;

        public ConnectThread(BluetoothDevice device) {
            // Use a temporary object that is later assigned to mmSocket,
            // because mmSocket is final
            BluetoothSocket tmp = null;
            mmDevice = device;

            // Get a BluetoothSocket to connect with the given BluetoothDevice
            try {
                // MY_UUID is the app's UUID string, also used by the server code
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) { }
            mmSocket = tmp;
        }

        public void run() {
            // Cancel discovery because it will slow down the connection
            mAdapter.cancelDiscovery();

            try {
                // Connect the device through the socket. This will block
                // until it succeeds or throws an exception
                mmSocket.connect();
            } catch (IOException connectException) {
                // Unable to connect; close the socket and get out
                try {
                    mmSocket.close();
                } catch (IOException closeException) { }
                return;
            }

            // Do work to manage the connection (in a separate thread)
            //manageConnectedSocket(mmSocket);
        }

        /** Will cancel an in-progress connection, and close the socket */
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) { }
        }
    }

    class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket) {
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the input and output streams, using temp objects because
            // member streams are final
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) { }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            byte[] buffer = new byte[1024];  // buffer store for the stream
            int bytes; // bytes returned from read()

            // Keep listening to the InputStream until an exception occurs
            while (true) {
                try {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);
                    // Send the obtained bytes to the UI activity
                    mHandler.obtainMessage(MainRemote.MESSAGE_READ, bytes, -1, buffer)
                            .sendToTarget();
                    Log.d("Blue","message recieved!:  " + bytes);
                } catch (IOException e) {
                    break;
                }
            }
        }

        /* Call this from the main activity to send data to the remote device */
        public void write(byte[] bytes) {
            try {
                mmOutStream.write(bytes);
            } catch (IOException e) { }
        }

        /* Call this from the main activity to shutdown the connection */
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) { }
        }
    }
    /**
     * Start the ConnectedThread to begin managing a Bluetooth connection
     * @param socket  The BluetoothSocket on which the connection was made
     * @param device  The BluetoothDevice that has been connected
     */
    public synchronized void connected(BluetoothSocket socket, BluetoothDevice
            device) {
        //if (D) Log.d(TAG, "connected, Socket Type:" + socketType);

        // Cancel the thread that completed the connection
        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

        // Cancel the accept thread because we only want to connect to one device
        if (mSecureAcceptThread != null) {
            mSecureAcceptThread.cancel();
            mSecureAcceptThread = null;
        }
        if (mInsecureAcceptThread != null) {
            mInsecureAcceptThread.cancel();
            mInsecureAcceptThread = null;
        }

        // Start the thread to manage the connection and perform transmissions
        mConnectedThread = new ConnectedThread(socket);
        mConnectedThread.start();

        // Send the name of the connected device back to the UI Activity
        Message msg = mHandler.obtainMessage(MainRemote.MESSAGE_DEVICE_NAME);
        Bundle bundle = new Bundle();
        bundle.putString(MainRemote.DEVICE_NAME, device.getName());
        msg.setData(bundle);
        mHandler.sendMessage(msg);

        setState(STATE_CONNECTED);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
}

解决方案

Its not that nothing is happening. Its that the Activity is not recreated. Try overriding onStart() I bet this is getting called instead.

这篇关于Android的服务启动活动不一样的反应,我认为它应该的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆