我在Android开发方面没有太多经验。现在,我无法从服务的 onStartCommand 方法注册接收器。
用英语表示:我在一个 Activity 上有两个按钮(启动/停止服务)。当我单击“开始”按钮时,我不想运行将注册 BroadcastReceiver (SMS_RECEIVED) 的服务。收到短信时,我不想看到日志跟踪。但是我没看到!
似乎我无法注册我的广播接收器,但我知道我的服务正在运行(感谢日志)。
此外,我想让我的服务以及我的 BroadcastReceiver 持久化(如果我退出应用程序,我希望它在后台运行,即使我重新启动手机)。
谁能告诉我我的代码有什么问题?...也许可以帮我解决第二个问题.... :)
谢谢 !
这是我的代码:
--- 活动:主要 ---
package com.tuto.servicerunbroadcastreceiver;
import XYZ
public class Main extends Activity implements OnClickListener
{
Button bt_start;
Button bt_stop;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_start = (Button)findViewById(R.id.button1);
bt_start.setOnClickListener(this);
bt_stop = (Button)findViewById(R.id.button2);
bt_stop.setOnClickListener(this);
}
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.button1 :
{
Log.d("Button : ", "Button start");
startService(new Intent(this, svcMessage.class));
break ;
}
case R.id.button2 :
{
Log.d("Button : ", "Button stop");
stopService(new Intent(this, svcMessage.class));
break ;
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
--- 服务:svcMessage ---
package com.tuto.servicerunbroadcastreceiver;
import XYZ;
public class svcMessage extends Service
{
private static final String ACTION_RECEIVE_SMS = "android.provider.Telephony.SMS_RECEIVED";
private BroadcastReceiver br_receiver;
@Override
public IBinder onBind(Intent arg0)
{
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
final IntentFilter filter = new IntentFilter();
filter.addAction("ACTION_RECEIVE_SMS");
Log.d("Service : ", "start");
this.br_receiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
Log.d("LOG : ", "onReceive");
}
};
this.registerReceiver(this.br_receiver, filter);
return (START_STICKY);
}
@Override
public void onDestroy()
{
super.onDestroy();
Log.d("Service : ", "destroy");
this.unregisterReceiver(this.br_receiver);
}
}
--- 清单.xml ---
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tuto.servicerunbroadcastreceiver"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.tuto.servicerunbroadcastreceiver.Main"
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 android:name="com.tuto.servicerunbroadcastreceiver.svcMessage">
</service>
</application>
</manifest>