最近项目中用到Service,我去,头一次接触这玩意啊。。。
1、
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
intent.setAction("com.example.fsdserialport.startService");
MainActivity.this.startService(intent);
}
}
2、
public class StartService extends Service{
private Timer timer = new Timer();
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
Log.d("fsd-Service", "onCreate");
timer.schedule(task, 0, 300); //启动一个timer
super.onCreate();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
Log.d("Service", "onDestroy");
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.d("Service", "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
private TimerTask task = new TimerTask() {
public void run() {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
};
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
break;
}
super.handleMessage(msg);
}
};
}
3、
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.fsdserialport"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<!-- 开机自动启动权限 -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.fsdserialport.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>
<!-- 注册service -->
<service android:name="com.example.fsdserialport.StartService"
android:permission="oem.permission.SENDMAIL"
>
<intent-filter>
<action android:name="com.example.fsdserialport.startService"/>
</intent-filter>
</service>
</application>
<!-- service权限 -->
<permission android:protectionLevel="normal" android:name="oem.permission.SENDMAIL">
</permission>
</manifest>
加红处,如果没有的话,可能会有问题;这个我也是初次玩耍