Android - 应用程序必须在后台运行

时间:2016-01-06 14:00:31

标签: android bluetooth broadcastreceiver

我希望我的应用程序必须在后台运行。该应用程序主要用于发送基于IBeacons的推送通知,即Apple提供的低功耗蓝牙技术。 这是很好的我的应用程序能够获得通知但它应该处于打开模式(应该打开应用程序)。但我希望我的应用程序必须在后台运行,就像用户进入IBeacon接近范围时,它必须在内部获得通知。

MainClass:

public class MainActivity extends Activity {
private static final String ESTIMOTE_PROXIMITY_UUID = "B9407F30-F5F8-466E-AFF9-25556B57FE6D";
private static final Region ALL_ESTIMOTE_BEACONS = new Region("regionId",
        ESTIMOTE_PROXIMITY_UUID, null, null);
protected static final String TAG = "EstimoteiBeacon";
BeaconManager beaconManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final TextView tx = (TextView) findViewById(R.id.textView1);
    final List<Integer> test1 = new ArrayList<Integer>();
    beaconManager = new BeaconManager(this);
    beaconManager.connect(new BeaconManager.ServiceReadyCallback() {
        @Override
        public void onServiceReady() {
             final ArrayList AList = new ArrayList();
            try {
                beaconManager.startRanging(ALL_ESTIMOTE_BEACONS);
                beaconManager
                        .setRangingListener(new BeaconManager.RangingListener() {
                            @Override
                            public void onBeaconsDiscovered(Region arg0,
                                    List<Beacon> beacons) {
                                for (Beacon beacon : beacons) {
                                    int major = beacon.getMajor();
                                    test1.add(major);
                                    AList.add(major);
                                    Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                                    intent.putIntegerArrayListExtra("test", (ArrayList<Integer>) test1);
                                    tx.setText(String.valueOf(major));
                                    startActivity(intent);
                                }
                            }
                        });
                } catch (RemoteException e) {
                Log.e("error", "Cannot start ranging", e);
            }
        }
    });
}
// ---stop ranging for beacons when activity is killed---
@Override
protected void onStop() {
    super.onStop();
    try {
        beaconManager.stopRanging(ALL_ESTIMOTE_BEACONS);
    } catch (RemoteException e) {
        Log.e     
        (TAG, "Cannot stop", e);
    }
}}

二等

public class SecondActivity extends Activity {
String name,str;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second);
    //Bundle extras = getIntent().getExtras();
    TextView tv1 = (TextView) findViewById(R.id.textView1);
    TextView tv2 = (TextView) findViewById(R.id.textView2);
    TextView tv3 = (TextView) findViewById(R.id.textView3);
    Intent intent=getIntent();
    ArrayList<Integer> test = intent.getIntegerArrayListExtra("test");

    tv1.setText(test.get(0).toString());
    tv2.setText(test.get(1).toString());
    tv3.setText(test.get(2).toString());
    String loginRequest = "http://172.17.13.10:8080/RESTfulDemoDerby/webresources/com.mss.mmxregistration/Message?maxvalue=32623";
    Log.e("retalier url", loginRequest);
    HttpGet request = new HttpGet(loginRequest);
    Bluetooth loginTask = new Bluetooth(
            SecondActivity.this, request);
    loginTask.execute();
}
class Bluetooth extends Bluetoothtask {
    public Bluetooth(Context context, HttpRequestBase request) {
        super(context, request);
        // TODO Auto-generated constructor stub
    }
    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub

        super.onPostExecute(result);

        if (result != null) {
            DocumentBuilderFactory factory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder builder;
            InputSource is;
            try {
                factory.setNamespaceAware(true);
                builder = factory.newDocumentBuilder();
                is = new InputSource(new StringReader(result));
                Document doc = builder.parse(is);
                NodeList list = doc.getElementsByTagName("Payload");
                result = list.item(0).getTextContent();
            } catch (ParserConfigurationException e) {
            } catch (SAXException e) {
            } catch (IOException e) {
            }
            JSONObject jsonObj;
            Gson gson = new Gson();
            try {
                jsonObj = new JSONObject(result);
            Log.e("Result", result);
            JSONObject jsonResponse;
              try {
            jsonResponse = new JSONObject(result);
            JSONArray cast = jsonResponse.getJSONArray("result");
            for (int i=0; i<cast.length(); i++) {
                JSONObject actor = cast.getJSONObject(i);
                 name = actor.getString("message");

            }
              } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Context context = getApplicationContext();
                   CharSequence text = "TURNING_ON BLUETOOTH";
                   int duration = Toast.LENGTH_LONG;
                   Toast toast = Toast.makeText(context, text, 15);
                   toast.show();
             NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
              @SuppressWarnings("deprecation")
              Notification notification = new Notification(R.drawable.ic_launcher,
                "New Message", System.currentTimeMillis());

               Intent notificationIntent = new Intent(SecondActivity.this, SecondActivity.class);
              PendingIntent pendingIntent = PendingIntent.getActivity(SecondActivity.this, 0,
                notificationIntent, 0);

               notification.setLatestEventInfo(SecondActivity.this, "Title",
                       name, pendingIntent);
              notificationManager.notify(9999, notification);
            } catch (Exception e) {
            }
        }
    }
}@Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

}

我们可以使用广播接收器来运行后台应用程序,但为此我们将如何实现此示例。

1 个答案:

答案 0 :(得分:1)

不幸的是,你已经建立了围绕Asynctasks和活动的一切,这些活动不能满足你的目标。您想要查找services

一旦您将逻辑移至服务,您就会想要根据广播接收器或持久通知启动/停止该服务。然后,如果您愿意,您的活动可以绑定到您的服务以从中获取更多信息,或者您可以使用其他形式的服务 - &gt;活动通信,如广播。

请注意,这可能是一个电池滤水器,因此您希望为您的用户提供关闭或至少选择加入/退出的功能。