android background service 是背景程式執行
只要你有開啟APP,即使你返回桌面,做其他事
他仍然會繼續執行
通常能用來做手機訊息通知的用途
以下是我的程式碼
MainActivity.java
@SuppressLint("NewApi")
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
find();
}
private EditText acc;
private void find() {
acc=(EditText)findViewById(R.id.acc);
acc.setText("aaa");
Intent intent2 = new Intent(MainActivity.this, myservice.class);
intent2.putExtra("ACCOUNT", name_str);
startService(intent2);
}
}
接下來是myservice.java
@SuppressLint("NewApi") public class myservice extends Service {
private Handler handler = new Handler();
String account="q";
@Override
public IBinder onBind(Intent intent) {
return null;
}
private Intent getIntent() {
return null;
}
@Override
public void onStart(Intent intent, int startId) {
account = intent.getStringExtra("ACCOUNT");
handler.postDelayed(showTime, 1000);
super.onStart(intent, startId);
}
@Override
public void onDestroy() {
handler.removeCallbacks(showTime);
super.onDestroy();
}
private void testNotification() {
Notification.Builder builder = new Notification.Builder(this);
builder.setSmallIcon(R.drawable.ic_launcher)
.setPriority(Notification.PRIORITY_HIGH)
.setOngoing(false);
builder.setContentText("待簽核");
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(1, builder.build());
}
private Runnable showTime = new Runnable() {
public void run() {
testNotification();
handler.postDelayed(this, 1000);
}
};
}
記得要在mainfest.xml中加上這句
<service android:name=".myservice"/>
以下是xml檔
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.leave.MainActivity" >
<EditText
android:id="@+id/acc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginLeft="16dp"
android:layout_marginTop="46dp"
android:hint="帳號"
android:ems="10" >
<requestFocus />
</EditText>
</RelativeLayout>
以上,開啟APP他就會背景執行,並且發送通知囉~
留言列表