我是android的新手,我正在学习android中的服务,我创建了一个片段,其中有一个按钮。点击该按钮我需要显示一个消息。
这是我的服务类 -
public class BackgroundSoundService extends Service {
private static final String TAG = null;
@Override
public void onCreate() {
super.onCreate();
Log.d("tagg", "onCreate: inside service");
Toast.makeText(getApplication(), "This is my Toast message!", Toast.LENGTH_LONG).show();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
当我点击片段类中的按钮时,我需要为消息干杯。 这是我的片段类 -
public class ConnectFragment extends Fragment {
Button service_btn;
public ConnectFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_connect, container, false);
service_btn = (Button) rootView.findViewById(R.id.service_button);
service_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//start_service();
Intent svc = new Intent(getActivity(), BackgroundSoundService.class);
try {
startActivity(svc);
} catch (Exception e) {
Log.d("tagg", "start_service:excception " + e);
}
}
});
return rootView;
}
public void start_service() {
Intent svc = new Intent(getActivity(), BackgroundSoundService.class);
}
}
现在我得到一个例外
start_service:excception android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.arjunh.navigationdrawer/com.example.arjunh.navigationdrawer.BackgroundSoundService}; have you declared this activity in your AndroidManifest.xml?
答案 0 :(得分:0)
在AndroidManifest.xml文件中添加服务
<service android:name=".BackgroundSoundService">
并从像
这样的片段开始服务getContext().startService(new Intent(getContext(),BackgroundSoundService.class));
我希望它对你有所帮助。