后台的Android应用

时间:2016-07-04 22:43:18

标签: java android android-studio android-sensors

我必须创建应用程序并希望在手机正常工作时使用它,目前我的代码是:

Android Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.plan.pedometer">
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:enabled="true"
                 android:name=".PedometerService"/>
        <receiver
            android:name=".receiver.StartPedometerServiceAtBootReceiver"
            android:label="StartPedometerServiceAtBootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

StartPedometerServiceAtBootReceiver:

public class StartPedometerServiceAtBootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
            Intent serviceIntent = new Intent(context, PedometerService.class);
            context.startService(serviceIntent);
        }
    }
}

服务:

public class PedometerService extends IntentService {

    private int Steps=0;

    public PedometerService() {
        super("Pedometer_Worker_Thread");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        putInSharedPreferences();
        synchronized (this) {
            try {
                wait(1000000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void putInSharedPreferences(){
        stepsNumbers = getApplicationContext().getSharedPreferences("stepsData", MODE_PRIVATE);
        editorStepsNumbers=stepsNumbers.edit();
        editorStepsNumbers.putInt(String.valueOf(STEPS),Steps).apply();
    }

}

如果我在Service中启动MainActivity,则可以使用

Intent intent = new Intent(getApplication(),PedometerService.class);
                startService(intent);

并且服务正在后台运行但是当我重新启动手机时没有任何反应并且服务无法启动。 我还有一个问题,这是Pedometer应用程序,我应该在服务中放置onSensorChange方法?在onHandleIntent()中创建类似while(1)的东西并将其放在那里?

更新 - 我的实际代码是:

我遵循了本教程https://github.com/codepath/android_guides/wiki/Starting-Background-Services 并尝试使用WakefulBroadcastReceiver AndroidManifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.plan.pedomoter">
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name="com.plan.pedomoter.MyTestService"
            android:exported="false"/>
        <receiver android:name="com.plan.pedomoter.BootBroadcastReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

MainActivity:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    @Override
    protected void onStart() {
        super.onStart();
        launchTestService();
    }
    public void launchTestService() {
        // Construct our Intent specifying the Service
        Intent i = new Intent(this, MyTestService.class);
        // Add extras to the bundle
        i.putExtra("foo", "bar");
        // Start the service
        startService(i);
    }
}

接收器:

public class BootBroadcastReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Launch the specified service when this message is received
        Intent startServiceIntent = new Intent(context, MyTestService.class);
        startWakefulService(context, startServiceIntent);
    }
}

服务:

public class MyTestService extends IntentService {
    Handler handler;
    // Must create a default constructor
    public MyTestService() {
        // Used to name the worker thread, important only for debugging.
        super("test-service");
    }
    @Override
    public void onCreate() {
        super.onCreate(); // if you override onCreate(), make sure to call super().
        // If a Context object is needed, call getApplicationContext() here.
        handler = new Handler();
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        WakefulBroadcastReceiver.completeWakefulIntent(intent);
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MyTestService.this, "start", Toast.LENGTH_LONG).show();
                int i = 0;
            }
        });
        int i=0;
        while(true){
            i++;
            // Do some work here
            if(i>1000)
                i=0;
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(MyTestService.this, "stop", Toast.LENGTH_SHORT).show();
    }
}

我在MyTestService中使用while(true)来检查应用程序是否在后台运行,在项目中我将使用传感器(这是计步器应用程序)然后我想从教程中添加类似MyAlarmReceiver的内容来发送数据到服务器一天几次。

2 个答案:

答案 0 :(得分:2)

试试这个 的的Manifest.xml

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.mkonuk.rebootapplication">

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <service android:name=".MyService"/>

        <receiver android:name=".MyBootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>


        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

<强> MainActivity

    public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService(new Intent(getBaseContext(),MyService.class));
    }
}

<强>为MyService

 public class MyService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(getApplicationContext(),"Service started",Toast.LENGTH_LONG).show();
        return START_STICKY;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(getApplicationContext(),"Service Destroyed",Toast.LENGTH_LONG).show();
    }

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

<强> MyBootReceiver

    public class MyBootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent service  = new Intent(context,MyService.class);
        context.startService(service);
    }
}

我已经测试了应用程序启动服务何时启动,即使你的应用程序销毁服务也将重新启动。即使重启android设备服务也将启动。

第二个问题: 如果您将传感器与服务一起使用,则需要注册传感器侦听器并在服务销毁时取消注册传感器侦听器,oncreate方法覆盖传感器对象并创建传感器和传感器管理器。在onstartCommand方法中注册生成的传感器侦听器传感器管理器对象,在服务销毁时取消注册侦听器 你可以查看这个链接 Accelemeter in android

如果要将消息从服​​务发送到活动,则必须实现onbind()方法,活动需要绑定服务检查此链接 bind activity on service using sensor

bind/unbind service

答案 1 :(得分:0)

你好,我有点新,并寻找一些帮助,(这不是一个答案)我可以添加任何其他评论我试图执行类似的应用程序,我跟着什么mithat显示,然后当我关闭我的mobili它似乎开始了,但就在我把我的手机密码时,它似乎是一个系统干杯,上面写着“app Stop”,所以我无法得到它。即使我从“最近的应用程序”中扫描应用程序,它也会显示“app Stop” 我想永远运行它, 感谢