我正在尝试在Android Studio中创建Android应用。 该应用程序主要是一个后台服务,每15秒左右向服务器发送一些信息。 我创建了一个空活动,启动接收器和服务类,但它不起作用。 有人可以帮助我,并解释为什么它不起作用。
相关文件:
MainActivity.java
package nl.robinvandervliet.robinsapp.app;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
public class MainActivity extends ActionBarActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
finish();
}
}
BootReceiver.java
package nl.robinvandervliet.robinsapp.app;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
context.startService(new Intent(context, RobinsService.class));
}
}
RobinsService.java
package nl.robinvandervliet.robinsapp.app;
import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class RobinsService extends Service
{
private Runnable runnable = new Runnable()
{
@Override
public void run()
{
//Opening connection to the server.
while (true)
{
//Sending some data to the server.
//Sleeping for around 15 seconds.
}
//Dead code, should never reach this place.
}
};
public IBinder onBind(Intent intent)
{
return null;
}
@Override
public void onCreate()
{
new Thread(runnable).start();
Notification notification = new Notification.Builder(getApplicationContext()).setContentTitle("MyService is running!").setContentTitle("(more information later)").build();
startForeground(1, notification);
Toast.makeText(getApplicationContext(), "Service created!", Toast.LENGTH_LONG).show();
}
}
的AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nl.robinvandervliet.robinsapp.app" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="nl.robinvandervliet.robinsapp.app.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="nl.robinvandervliet.robinsapp.app.BootReceiver" android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name="nl.robinvandervliet.robinsapp.app.RobinsService" android:exported="false" />
</application>
<uses-permission android:name="android.permission.BATTERY_STATS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</manifest>
谢谢,罗宾。