how to cancel a download when user clicked in android - java

i am new to download manager side of android, i can't cancel the download when user clicked a button,i am putting the current id of request but still havent solve it, help me thnks in advance
heres the main class
public class DownloadManagerActivity extends Activity {
private long enqueue; private DownloadManager dm; private long downloadReference; Query query; Cursor c; String action;
long downloadId;
Request request;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
query = new Query();
query.setFilterById(enqueue);
c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
//
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
Toast.makeText(DownloadManagerActivity.this, "Download Complete", Toast.LENGTH_LONG).show();
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public void onClick(View view) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
request = new Request(Uri.parse("http://192.168.10.6/mytv/mashup.mp4"));
enqueue = dm.enqueue(request);
}
public void showDownload(View view) {
Intent i = new Intent();
i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(i);
}
public void cancelDownload(View view) {
//downloadReference= intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
downloadReference = dm.enqueue(request);
dm.remove(downloadReference);
Toast.makeText(DownloadManagerActivity.this, "Download Cancelled", Toast.LENGTH_SHORT).show();
}

downloadReference = dm.enqueue(request) create a new task and return a new id.You should use the previous id.
public void cancelDownload(View view) {
//downloadReference= intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
//downloadReference = dm.enqueue(request);
dm.remove(enqueue );
Toast.makeText(DownloadManagerActivity.this, "Download Cancelled", Toast.LENGTH_SHORT).show();
}

Related

Does Service needs another parser?

I have already been fetched data from instagram api. But i cannot reach that data to use it on my service. I have tried all methods that i know.
**Here is my main object: ** If my followers count is increases or decreases, notify, And check that for every 5 min.(I am still working on it. There are lots of misses yet.)
**Here is my main question: ** Do i really have to create a new parser to fetch data that i already have or what should i build?
If you have any sample or Articles for this case, that would be useful.
I heard about Csv file. Is that can be useful to import ?
PS: I learned java and android studio yet. I am pretty newbie.
public class MyService extends Service {
private InstagramApp mApp;
private HashMap<String, String> userInfoHashmap = new HashMap<String, String>();
#Nullable
#Override
public IBinder onBind(Intent intent) { return null; }
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mApp = new InstagramApp(this, ApplicationData.CLIENT_ID,
ApplicationData.CLIENT_SECRET, ApplicationData.CALLBACK_URL);
Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
String xx=userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY);
getnotification(xx);
}
}, 0, 5000);
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this,"Service Stopped", Toast.LENGTH_LONG).show();
}
public void getnotification(String xx){
//String foo=(userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY));
// int fo= Integer.parseInt(foo);
// Toast.makeText(this, xx, Toast.LENGTH_LONG).show();
NotificationManager notificationmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pintent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
//PendingIntent pintent = PendingIntent.getActivities(this,(int)System.currentTimeMillis(),intent, 0);
Notification notif = new Notification.Builder(this)
.setSmallIcon(R.drawable.common_full_open_on_phone)
.setContentTitle("Notifications "+xx)
.setContentText("Followed by="+ userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY))
.setContentIntent(pintent)
.build();
notificationmgr.notify(0,notif);
}
/* Uri uri = Uri.parse("http://instagram.com/");
Intent likeIng = new Intent(Intent.ACTION_VIEW, uri);
likeIng.setPackage("com.instagram.android");
try {
startActivity(likeIng);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://instagram.com/xxx")));
}*/
}
Here is my MainActivity
public class MainActivity extends AppCompatActivity implements OnClickListener {
private InstagramApp mApp;
private Button btnConnect;
private Button btnMe, btnOS,btnCS;
private HashMap<String, String> userInfoHashmap = new HashMap<String, String>();
ViewGroup myLayout;
private FirebaseAnalytics mFirebaseAnalytics;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
myLayout = (ViewGroup)findViewById(R.id.myLayout);
mApp = new InstagramApp(this, ApplicationData.CLIENT_ID,
ApplicationData.CLIENT_SECRET, ApplicationData.CALLBACK_URL);
mApp.setListener(new OAuthAuthenticationListener() {
#Override
public void onSuccess() {
mApp.fetchUserName(handler);
}
#Override
public void onFail(String error) {
Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT)
.show();
}
}
);
setWidgetReference();
bindEventHandlers();
if (mApp.hasAccessToken()) {
btnConnect.setText("Disconnect");
mApp.fetchUserName(handler);
}
}
private void setWidgetReference() {
btnConnect = (Button) findViewById(R.id.btnConnect);
btnMe = (Button) findViewById(R.id.btnMy);
btnOS = (Button) findViewById(R.id.btnOS);
btnCS = (Button) findViewById(R.id.btnCS);
}
private void bindEventHandlers() {
btnConnect.setOnClickListener(this);
btnMe.setOnClickListener(this);
btnOS.setOnClickListener(this);
btnCS.setOnClickListener(this);
}
String log="log";
#Override
public void onClick(View v) {
if (v == btnConnect) {
connectOrDisconnectUser();
} else {
String url = "";
if (v == btnMe) {
Log.v(log,"info show");
displayInfoDialogView();
//TODO Usersa string koy. Yeni hesap için.
// url = "https://api.instagram.com/v1/users/self"+ userInfoHashmap.get(InstagramApp.TAG_ID)+ "/?access_token=" + mApp.getTOken(); imageView.setTag(userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE));String imageName = (String) imageView.getTag();String axe=(String) userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE);image.setImageResource(axe);
}
else if (v == btnOS) {
Log.v(log,"Service started");
startService(new Intent(getBaseContext(),MyService.class));
// url = "https://api.instagram.com/v1/users/self/media/recent"+ userInfoHashmap.get(InstagramApp.TAG_ID)+ "/followed-by?access_token="+ mApp.getTOken();
}
//startActivity(new Intent(MainActivity.this, Relationship.class).putExtra("userInfo", url));
else if(v==btnCS){
Log.v(log,"Service closed");
stopService(new Intent(getBaseContext(),MyService.class));
}
}
}
public void goBack(View v){
setContentView(R.layout.activity_main);
}
private void connectOrDisconnectUser() {
if (mApp.hasAccessToken()) {
final AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage("Disconnect from Instagram?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
mApp.resetAccessToken();
btnConnect.setText("Connect");
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
mApp.authorize();
}
}
private Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
if (msg.what == InstagramApp.WHAT_FINALIZE) {
userInfoHashmap = mApp.getUserInfo();
btnConnect.setText("Disconnect");
} else if (msg.what == InstagramApp.WHAT_ERROR) {
Toast.makeText(MainActivity.this, "Check your network.",
Toast.LENGTH_SHORT).show();
}
return false;
}
});
#Override
protected void onStart() {
super.onStart();
Toast.makeText(this, "Welcome to onStart", Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
Toast.makeText(this, "Welcome to onResume", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
super.onPause();
Toast.makeText(this, "It is onPause", Toast.LENGTH_SHORT).show();
}
#Override
protected void onStop() {
super.onStop();
Toast.makeText(this, "Stopped", Toast.LENGTH_SHORT).show();
}
#Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Bye Bye :((", Toast.LENGTH_SHORT).show();
}
private void displayInfoDialogView() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle(userInfoHashmap.get(InstagramApp.TAG_USERNAME));
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.activity_follower_list, null);
alertDialog.setView(view);
TextView tvName = (TextView) view.findViewById(R.id.textView3);
TextView tvNoOfFollwers = (TextView) view.findViewById(R.id.textView2);
TextView tvNoOfFollowing = (TextView) view.findViewById(R.id.textView4);
//new ImageLoader(MainActivity.this).DisplayImage(userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE), ivProfile);
tvName.setText(userInfoHashmap.get(InstagramApp.TAG_USERNAME));
tvNoOfFollowing.setText(userInfoHashmap.get(InstagramApp.TAG_FOLLOWS));
tvNoOfFollwers.setText(userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY));
alertDialog.create().show();
}
public void getnotification(){
String xx = userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY);
/* Toast.makeText(this, xx, Toast.LENGTH_LONG)
.show();
*/
if (xx!=xx ) {
NotificationManager notificationmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Intent intent = new Intent(this, resultpage.class);
// PendingIntent pintent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
// PendingIntent pintent = PendingIntent.getActivities(this,(int)System.currentTimeMillis(),intent, 0);
Notification notif = new Notification.Builder(this)
.setSmallIcon(R.drawable.common_google_signin_btn_text_dark_pressed)
.setContentTitle("Bu bir Bildirimdir!")
.setContentText("Bu bildirimin içeriğidir.")
//.setContentIntent(pintent)
.build();
notificationmgr.notify(0,notif);
}
}
}
The only solution that i found is the adding parser to your service to reach data from api. None of the the method can access to reach data from service to activity.
I added this class to reach api data on service.
public void lilParser() throws IOException, JSONException{
URL url = new URL(API_URL + "/users/" + mSession.getId()
+ "/?access_token=" + mAccessToken);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
String response = Utils.streamToString(urlConnection
.getInputStream());
System.out.println(response);
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
JSONObject data_obj = jsonObj.getJSONObject("data");
JSONObject counts_obj = data_obj.getJSONObject("counts");
String name = jsonObj.getJSONObject("data").getString("full_name");
String bio =jsonObj.getJSONObject("data").getString("bio");
String counts=jsonObj.getJSONObject("data").getString("counts");
userInfoHashmap.put(TAG_FOLLOWED_BY,counts_obj.getString(TAG_FOLLOWED_BY));
Log.i(TAG,"followedby=>[" + counts + "]");
}
And, Here is my onCreate. You can check The data if it is changed or not.
#Override
public void onCreate() {
Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
String fo = userInfoHashmap.get(TAG_FOLLOWED_BY);
try {
lilParser();
}
catch (IOException e) {e.printStackTrace();}
catch (JSONException e) {e.printStackTrace();}
if(new String(userInfoHashmap.get(TAG_FOLLOWED_BY)).equals(fo)==true){}
else {
getnotification();
}
}
}, 0, 30000);
}
PS: I published my code, that may help someone else. I am still newbie.

Video and audio call 2 Android devices - webrtc

I'm trying do develop Android app which will send audio and video via webrtc protocol between devices. This code works well with Android and web interface, but not between two Androids. Every time connection is opened and popup says that devices are connected, but there is no sound and picture. I tried a lot of things, but nothing helped. Dependencies and permissions are ok. Used my own pub and sub keys from PubNub. It opens connection 1 of 20 times between two Androids, so I think that something isn't working well here.
Followed this tutorial to create app: tutorial
I found this error image
Camera is crashing somewhere, but I really don't know why.
public static final String VIDEO_TRACK_ID = "videoPN";
public static final String AUDIO_TRACK_ID = "audioPN";
public static final String LOCAL_MEDIA_STREAM_ID = "localStreamPN";
private PnRTCClient pnRTCClient;
private VideoSource localVideoSource;
private VideoRenderer.Callbacks localRender;
private VideoRenderer.Callbacks remoteRender;
private GLSurfaceView mVideoView;
private String username;
private class MyRTCListener extends PnRTCListener {
#Override
public void onLocalStream(final MediaStream localStream) {
VideoChatActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if(localStream.videoTracks.size()==0) return;
localStream.videoTracks.get(0).addRenderer(new VideoRenderer(localRender));
}
});
}
#Override
public void onAddRemoteStream(final MediaStream remoteStream, final PnPeer peer) {
VideoChatActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(VideoChatActivity.this,"Connected to " + peer.getId(), Toast.LENGTH_SHORT).show();
try {
if(remoteStream.videoTracks.size()==0) return;
remoteStream.videoTracks.get(0).addRenderer(new VideoRenderer(remoteRender));
VideoRendererGui.update(remoteRender, 0, 0, 100, 100, VideoRendererGui.ScalingType.SCALE_ASPECT_FILL, false);
VideoRendererGui.update(localRender, 72, 72, 25, 25, VideoRendererGui.ScalingType.SCALE_ASPECT_FIT, true);
}
catch (Exception e){ e.printStackTrace(); }
}
});
}
#Override
public void onPeerConnectionClosed(PnPeer peer) {
Intent intent = new Intent(VideoChatActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videochatactivity);
Bundle extras = getIntent().getExtras();
if (extras == null || !extras.containsKey(Constants.USER_NAME)) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
Toast.makeText(this, "Need to pass username to VideoChatActivity in intent extras (Constants.USER_NAME).",
Toast.LENGTH_SHORT).show();
finish();
return;
}
this.username = extras.getString(Constants.USER_NAME, "");
PeerConnectionFactory.initializeAndroidGlobals(
this, // Context
true, // Audio Enabled
true, // Video Enabled
true, // Hardware Acceleration Enabled
null); // Render EGL Context
PeerConnectionFactory pcFactory = new PeerConnectionFactory();
this.pnRTCClient = new PnRTCClient(Constants.PUB_KEY, Constants.SUB_KEY, this.username);
int camNumber = VideoCapturerAndroid.getDeviceCount();
String frontFacingCam = VideoCapturerAndroid.getNameOfFrontFacingDevice();
String backFacingCam = VideoCapturerAndroid.getNameOfBackFacingDevice();
VideoCapturerAndroid capturer = (VideoCapturerAndroid) VideoCapturerAndroid.create(frontFacingCam);
localVideoSource = pcFactory.createVideoSource(capturer, this.pnRTCClient.videoConstraints());
VideoTrack localVideoTrack = pcFactory.createVideoTrack(VIDEO_TRACK_ID, localVideoSource);
AudioSource audioSource = pcFactory.createAudioSource(this.pnRTCClient.audioConstraints());
AudioTrack localAudioTrack = pcFactory.createAudioTrack(AUDIO_TRACK_ID, audioSource);
MediaStream mediaStream = pcFactory.createLocalMediaStream(LOCAL_MEDIA_STREAM_ID);
mediaStream.addTrack(localVideoTrack);
mediaStream.addTrack(localAudioTrack);
this.mVideoView = (GLSurfaceView) findViewById(R.id.gl_surface);
VideoRendererGui.setView(mVideoView, null);
remoteRender = VideoRendererGui.create(0, 0, 100, 100, VideoRendererGui.ScalingType.SCALE_ASPECT_FILL, false);
localRender = VideoRendererGui.create(0, 0, 100, 100, VideoRendererGui.ScalingType.SCALE_ASPECT_FILL, true);
this.pnRTCClient.attachRTCListener(new MyRTCListener());
this.pnRTCClient.attachLocalMediaStream(mediaStream);
this.pnRTCClient.listenOn(this.username);
this.pnRTCClient.setMaxConnections(1);
if (extras.containsKey(Constants.JSON_CALL_USER)) {
String callUser = extras.getString(Constants.JSON_CALL_USER, "");
connectToUser(callUser);
}
}
public void connectToUser(String user) {
this.pnRTCClient.connect(user);
}
public void hangup(View view) {
this.pnRTCClient.closeAllConnections();
startActivity(new Intent(VideoChatActivity.this, MainActivity.class));
}
#Override
protected void onDestroy() {
super.onDestroy();
if (this.localVideoSource != null) {
localVideoSource.stop();
}
if (this.pnRTCClient != null) {
this.pnRTCClient.onDestroy();
this.pnRTCClient.closeAllConnections();
}
}
Here is MainActivity if it will help:
private SharedPreferences mSharedPreferences;
private TextView mUsernameTV;
private EditText mCallNumET;
// private Pubnub mPubNub;
private String username;
private Pubnub mPubNub;
public void initPubNub() {
String stdbyChannel = this.username + Constants.STDBY_SUFFIX;
this.mPubNub = new Pubnub(Constants.PUB_KEY, Constants.SUB_KEY);
this.mPubNub.setUUID(this.username);
try {
this.mPubNub.subscribe(stdbyChannel, new Callback() {
#Override
public void successCallback(String channel, Object message) {
Log.d("MA-success", "MESSAGE: " + message.toString());
if (!(message instanceof JSONObject)) return; // Ignore if not JSONObject
JSONObject jsonMsg = (JSONObject) message;
try {
if (!jsonMsg.has(Constants.JSON_CALL_USER)) return;
String user = jsonMsg.getString(Constants.JSON_CALL_USER);
// Consider Accept/Reject call here
Intent intent = new Intent(MainActivity.this, VideoChatActivity.class);
intent.putExtra(Constants.USER_NAME, username);
intent.putExtra(Constants.JSON_CALL_USER, user);
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} catch (PubnubException e) {
e.printStackTrace();
}
}
public void makeCall(View view){
String callNum = mCallNumET.getText().toString();
if (callNum.isEmpty() || callNum.equals(this.username)) {
Toast.makeText(this, "Enter a valid number.", Toast.LENGTH_SHORT).show();
}
dispatchCall(callNum);
}
public void dispatchCall(final String callNum) {
final String callNumStdBy = callNum + Constants.STDBY_SUFFIX;
JSONObject jsonCall = new JSONObject();
try {
jsonCall.put(Constants.JSON_CALL_USER, this.username);
mPubNub.publish(callNumStdBy, jsonCall, new Callback() {
#Override
public void successCallback(String channel, Object message) {
Log.d("MA-dCall", "SUCCESS: " + message.toString());
Intent intent = new Intent(MainActivity.this, VideoChatActivity.class);
intent.putExtra(Constants.USER_NAME, username);
intent.putExtra(Constants.JSON_CALL_USER, callNum);
startActivity(intent);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.mSharedPreferences = getSharedPreferences(Constants.SHARED_PREFS, MODE_PRIVATE);
// Return to Log In screen if no user is logged in.
if (!this.mSharedPreferences.contains(Constants.USER_NAME)){
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
return;
}
this.username = this.mSharedPreferences.getString(Constants.USER_NAME, "");
this.mCallNumET = (EditText) findViewById(R.id.call_num);
this.mUsernameTV = (TextView) findViewById(R.id.main_username);
this.mUsernameTV.setText(this.username); // Set the username to the username text view
//TODO: Create and instance of Pubnub and subscribe to standby channel
// In pubnub subscribe callback, send user to your VideoActivity
initPubNub();
}
I will appreciate any help. Thanks to everybody.
when You run your application that time they ask sign in usename
that time you wrote your name
put that name in VideoChatActivity class
this.pnRTCClient.listenOn("your name when your wrote at signin time");
this.pnRTCClient.setMaxConnections(3);

MQTT Implementation Issue (Dale Lane Example)

I am running into an issue with the implementation of the Dale Lane MQTT solution.
I cannot seem to figure out how to retrieve the published message from the MQTT Client I am using.
I am not sure if I am utilizing the the onReceive() method incorrectly, but for now all I would like to do is log the broadcasted messages.
http://dalelane.co.uk/blog/?p=1599
The service I have implemented is exactly as listed here, I have no errors.
public class MQTTNotifier extends Activity implements OnClickListener {
String preferenceBrokerHost, preferenceBrokerTopic;
private StatusUpdateReceiver statusUpdateIntentReceiver;
private MQTTMessageReceiver messageIntentReceiver;
private EditText etBroker, etTopic;
Button btnSubscribe, btnStopService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mqttnotifier);
initValues();
// startService();
}
private void initValues() {
btnSubscribe = (Button) findViewById(R.id.btnSubscribe);
btnSubscribe.setOnClickListener(this);
btnStopService = (Button) findViewById(R.id.btnStopService);
btnStopService.setOnClickListener(this);
// if statement to see if sharedpreferences exist, if so reopen recievers
/*
* statusUpdateIntentReceiver = new StatusUpdateReceiver(); IntentFilter intentSFilter = new
* IntentFilter(MQTTService.MQTT_STATUS_INTENT); registerReceiver(statusUpdateIntentReceiver,
* intentSFilter);
*
* messageIntentReceiver = new MQTTMessageReceiver(); IntentFilter intentCFilter = new
* IntentFilter(MQTTService.MQTT_MSG_RECEIVED_INTENT); registerReceiver(messageIntentReceiver,
* intentCFilter);
*/
}
public class StatusUpdateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle notificationData = intent.getExtras();
String newStatus = notificationData.getString(MQTTService.MQTT_STATUS_MSG);
}
}
public class MQTTMessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle notificationData = intent.getExtras();
String newTopic = notificationData.getString(MQTTService.MQTT_MSG_RECEIVED_TOPIC);
String newData = notificationData.getString(MQTTService.MQTT_MSG_RECEIVED_MSG);
Log.e("NEW TOPIC", newTopic);
Log.e("NEW DATA", newData);
}
}
#Override
protected void onDestroy() {
unregisterReceiver(statusUpdateIntentReceiver);
unregisterReceiver(messageIntentReceiver);
}
private void startService() {
Intent svc = new Intent(this, MQTTService.class);
startService(svc);
}
private void stopService() {
Intent svc = new Intent(this, MQTTService.class);
stopService(svc);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.cancel(MQTTService.MQTT_NOTIFICATION_UPDATE);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnSubscribe:
etBroker = (EditText) findViewById(R.id.etBroker);
etTopic = (EditText) findViewById(R.id.etTopic);
preferenceBrokerHost = etBroker.getText().toString().trim();
preferenceBrokerTopic = etBroker.getText().toString().trim();
createSharedPreferences(preferenceBrokerHost, preferenceBrokerTopic);
establishRecievers();
startService();
break;
case R.id.btnStopService:
stopService();
}
}
private void createSharedPreferences(String broker, String topic) {
SharedPreferences settings = getSharedPreferences(MQTTService.APP_ID, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("broker", broker);
editor.putString("topic", topic);
editor.commit();
}
private void establishRecievers() {
statusUpdateIntentReceiver = new StatusUpdateReceiver();
IntentFilter intentSFilter = new IntentFilter(MQTTService.MQTT_STATUS_INTENT);
registerReceiver(statusUpdateIntentReceiver, intentSFilter);
messageIntentReceiver = new MQTTMessageReceiver();
IntentFilter intentCFilter = new IntentFilter(MQTTService.MQTT_MSG_RECEIVED_INTENT);
registerReceiver(messageIntentReceiver, intentCFilter);
}
}
It turns out that the issue was in regards to a simple mistake that was in regards to this line.
preferenceBrokerTopic = etBroker.getText().toString().trim();
I corrected the issue and now it corrects properly because it was not subscribing to the correct topic.
preferenceBrokerTopic = etTopic.getText().toString().trim();

Android MediaPlayer cannot play files that contain '#' character in the file name using Uri.parse(path)

From what I can tell, the Uri.parse in my code is causing my MediaPlayer to fail on audio files with special characters in the filename, like "#" and others. I cannot figure out how to resolve this issue. I want to be able to use special characters in my filenames. Here is the code that I think is causing the issue:
public void playAudio(int media) {
try {
switch (media) {
case LOCAL_AUDIO:
/**
* TODO: Set the path variable to a local audio file path.
*/
if (path == "") {
// Tell the user to provide an audio file URL.
Toast
.makeText(
MediaPlayerDemo_Audio.mp,
"Please edit MediaPlayer_Audio Activity, "
+ "and set the path variable to your audio file path."
+ " Your audio file must be stored on sdcard.",
Toast.LENGTH_LONG).show();
}
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setLooping(sound_loop);
mMediaPlayer.setDataSource(MediaPlayerDemo_Audio.mp, Uri.parse(path));
mMediaPlayer.prepare();
resetTimer();
startTimer();
mMediaPlayer.start();
Intent intent = new Intent(MediaPlayerDemo_Audio.PLAY_START);
sendBroadcast(intent);
break;
case RESOURCES_AUDIO:
/**
* TODO: Upload a audio file to res/raw folder and provide
* its resid in MediaPlayer.create() method.
*/
// mMediaPlayer = MediaPlayer.create(this, R.raw.test_cbr);
//mMediaPlayer.start();
}
//tx.setText(path);
} catch (Exception e) {
//Log.e(TAG, "error: " + e.getMessage(), e);
}
}
I am using MediaPlayerDemo_Audio.java to play sounds. As you can see from the above code, the mMediaPlayer.setDataSource(MediaPlayerDemo_Audio.mp, Uri.parse(path)); is calling the code to retrieve the file and media player, I think. I am not too skilled with android code yet. Here is the code for MediaPlayerDemo_Audio.java:
public class MediaPlayerDemo_Audio extends Activity {
public static String path;
private String fname;
private static Intent PlayerIntent;
public static String STOPED = "stoped";
public static String PLAY_START = "play_start";
public static String PAUSED = "paused";
public static String UPDATE_SEEKBAR = "update_seekbar";
public static boolean is_loop = false;
private static final int LOCAL_AUDIO=0;
private Button play_pause, stop;
private SeekBar seek_bar;
public static MediaPlayerDemo_Audio mp;
private AudioPlayerService mPlayerService;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.media_player_layout);
//getWindow().setTitle("SoundPlayer");
//getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
// android.R.drawable.ic_media_play);
play_pause = (Button)findViewById(R.id.play_pause);
play_pause.setOnClickListener(play_pause_clk);
stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(stop_clk);
seek_bar = (SeekBar)findViewById(R.id.seekBar1);
seek_bar.setMax(100);
seek_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
if (mPlayerService!=null) {
int seek_pos = (int) ((double)mPlayerService.getduration()*seekBar.getProgress()/100);
mPlayerService.seek(seek_pos);
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
}
});
play_pause.setText("Pause");
stop.setText("Stop");
//int idx = path.lastIndexOf("/");
//fname = path.substring(idx+1);
//tx.setText(path);
IntentFilter filter = new IntentFilter();
filter.addAction(STOPED);
filter.addAction(PAUSED);
filter.addAction(PLAY_START);
filter.addAction(UPDATE_SEEKBAR);
registerReceiver(mPlayerReceiver, filter);
PlayerIntent = new Intent(MediaPlayerDemo_Audio.this, AudioPlayerService.class);
if (AudioPlayerService.path=="") AudioPlayerService.path=path;
AudioPlayerService.sound_loop = is_loop;
startService(PlayerIntent);
bindService(PlayerIntent, mConnection, 0);
if (mPlayerService!=null && mPlayerService.is_pause==true) play_pause.setText("Play");
mp = MediaPlayerDemo_Audio.this;
}
private BroadcastReceiver mPlayerReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String act = intent.getAction();
if (act.equalsIgnoreCase(UPDATE_SEEKBAR)){
int val = intent.getIntExtra("seek_pos", 0);
seek_bar.setProgress(val);
TextView counter = (TextView) findViewById(R.id.time_view);
counter.setText(DateUtils.formatElapsedTime((long) (intent.getLongExtra("time", 0)/16.666)));
//tx.setText(fname);
}
else if (act.equalsIgnoreCase(STOPED)) {
play_pause.setText("Play");
seek_bar.setProgress(0);
stopService(PlayerIntent);
unbindService(mConnection);
mPlayerService = null;
TextView counter = (TextView) findViewById(R.id.time_view);
counter.setText(DateUtils.formatElapsedTime(0));
}
else if (act.equalsIgnoreCase(PLAY_START)){
play_pause.setText("Pause");
}
else if (act.equalsIgnoreCase(PAUSED)){
play_pause.setText("Play");
}
}
};
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
mPlayerService = ((AudioPlayerService.LocalBinder)arg1).getService();
if (mPlayerService.is_pause==true) {
play_pause.setText("Play");
seek_bar.setProgress(mPlayerService.seek_pos);
}
if (mPlayerService.mTime!=0) {
TextView counter = (TextView) findViewById(R.id.time_view);
counter.setText(DateUtils.formatElapsedTime((long) (mPlayerService.mTime/16.666)));
}
if (path.equalsIgnoreCase(AudioPlayerService.path)==false){
AudioPlayerService.path = path;
mPlayerService.restart();
}
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
mPlayerService = null;
}
};
private OnClickListener play_pause_clk = new OnClickListener() {
#Override
public void onClick(View arg0) {
if (mPlayerService!=null)
mPlayerService.play_pause();
else{
AudioPlayerService.path=path;
startService(PlayerIntent);
bindService(PlayerIntent, mConnection, 0);
}
}
};
private OnClickListener stop_clk = new OnClickListener() {
#Override
public void onClick(View arg0) {
if (mPlayerService==null) return;
mPlayerService.Stop();
}
};
#Override
protected void onDestroy() {
super.onDestroy();
// TODO Auto-generated method stub
}
}
How can I fix this issue so files can be parsed with special characters and played correctly in MediaPlayer? Am I missing something?
Maybe it would help to show the entire code for my AudioPlayerService:
public class AudioPlayerService extends Service {
public MediaPlayer mMediaPlayer;
protected long mStart;
public long mTime;
public int seek_pos=0;
public static boolean sound_loop = false;
public boolean is_play, is_pause;
public static String path="";
private static final int LOCAL_AUDIO=0;
private static final int RESOURCES_AUDIO=1;
private int not_icon;
private Notification notification;
private NotificationManager nm;
private PendingIntent pendingIntent;
private Intent intent;
#SuppressWarnings("deprecation")
#Override
public void onCreate() {
playAudio(LOCAL_AUDIO);
mTime=0;
is_play = true;
is_pause = false;
CharSequence ticker = "Touch to return to app";
long now = System.currentTimeMillis();
not_icon = R.drawable.play_notification;
notification = new Notification(not_icon, ticker, now);
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Context context = getApplicationContext();
intent = new Intent(this, MediaPlayerDemo_Audio.class);
pendingIntent = PendingIntent.getActivity(context, 0,intent, 0);
PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
//INCOMING call
//do all necessary action to pause the audio
if (is_play==true && is_pause==false){
play_pause();
}
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
//Not IN CALL
//do anything if the phone-state is idle
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
//do all necessary action to pause the audio
//do something here
if (is_play==true && is_pause==false){
play_pause();
}
}
super.onCallStateChanged(state, incomingNumber);
}
};//end PhoneStateListener
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
OnAudioFocusChangeListener myaudiochangelistener = new OnAudioFocusChangeListener(){
#Override
public void onAudioFocusChange(int arg0) {
//if (arg0 ==AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK){
if (is_play==true && is_pause==false){
play_pause();
}
//}
}
};
AudioManager amr = (AudioManager)getSystemService(AUDIO_SERVICE);
amr.requestAudioFocus(myaudiochangelistener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
}
#SuppressWarnings("deprecation")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Context context = getApplicationContext();
String title = "VoiceRecorder App";
CharSequence message = "Playing..";
notification.setLatestEventInfo(context, title, message,pendingIntent);
nm.notify(101, notification);
return START_STICKY;
}
public class LocalBinder extends Binder {
AudioPlayerService getService() {
return AudioPlayerService.this;
}
}
public void restart(){
mMediaPlayer.stop();
playAudio(LOCAL_AUDIO);
mTime=0;
is_play = true;
is_pause = false;
}
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
private final IBinder mBinder = new LocalBinder();
public void Stop()
{
mMediaPlayer.stop();
Intent intent1 = new Intent(MediaPlayerDemo_Audio.STOPED);
sendBroadcast(intent1);
resetTimer();
is_play=false;
is_pause=false;
}
public void play_pause()
{
if (is_play==false){
try {
mMediaPlayer.start();
startTimer();
is_play=true;
is_pause = false;
} catch (Exception e) {
//Log.e(TAG, "error: " + e.getMessage(), e);
}
Intent intent = new Intent(MediaPlayerDemo_Audio.PLAY_START);
sendBroadcast(intent);
}
else{
mMediaPlayer.pause();
stopTimer();
Intent intent1 = new Intent(MediaPlayerDemo_Audio.PAUSED);
sendBroadcast(intent1);
is_play = false;
is_pause = true;
}
}
public int getduration()
{
return mMediaPlayer.getDuration();
}
public void seek(int seek_pos)
{
mMediaPlayer.seekTo(seek_pos);
mTime = seek_pos;
}
public void playAudio(int media) {
try {
switch (media) {
case LOCAL_AUDIO:
/**
* TODO: Set the path variable to a local audio file path.
*/
if (path == "") {
// Tell the user to provide an audio file URL.
Toast
.makeText(
MediaPlayerDemo_Audio.mp,
"Please edit MediaPlayer_Audio Activity, "
+ "and set the path variable to your audio file path."
+ " Your audio file must be stored on sdcard.",
Toast.LENGTH_LONG).show();
}
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setLooping(sound_loop);
mMediaPlayer.setDataSource(MediaPlayerDemo_Audio.mp, Uri.parse(path));
mMediaPlayer.prepare();
resetTimer();
startTimer();
mMediaPlayer.start();
Intent intent = new Intent(MediaPlayerDemo_Audio.PLAY_START);
sendBroadcast(intent);
break;
case RESOURCES_AUDIO:
/**
* TODO: Upload a audio file to res/raw folder and provide
* its resid in MediaPlayer.create() method.
*/
// mMediaPlayer = MediaPlayer.create(this, R.raw.test_cbr);
//mMediaPlayer.start();
}
//tx.setText(path);
} catch (Exception e) {
//Log.e(TAG, "error: " + e.getMessage(), e);
}
}
#SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
long curTime = System.currentTimeMillis();
mTime += curTime-mStart;
mStart = curTime;
int pos = (int) ((double)mMediaPlayer.getCurrentPosition()*100/mMediaPlayer.getDuration());
seek_pos = pos;
Intent intent1 = new Intent(MediaPlayerDemo_Audio.UPDATE_SEEKBAR);
if (mMediaPlayer.isLooping()) intent1.putExtra("time", (long)mMediaPlayer.getCurrentPosition());
else intent1.putExtra("time", mTime);
intent1.putExtra("seek_pos", pos);
sendBroadcast(intent1);
if (mMediaPlayer.isPlaying()==false && mMediaPlayer.isLooping()==false){
mMediaPlayer.stop();
resetTimer();
Intent intent2 = new Intent(MediaPlayerDemo_Audio.STOPED);
sendBroadcast(intent2);
is_play=false;
}
if (mTime > 0) mHandler.sendEmptyMessageDelayed(0, 10);
};
};
private void startTimer() {
mStart = System.currentTimeMillis();
mHandler.removeMessages(0);
mHandler.sendEmptyMessage(0);
}
private void stopTimer() {
mHandler.removeMessages(0);
}
private void resetTimer() {
stopTimer();
mTime = 0;
}
#Override
public void onDestroy() {
super.onDestroy();
// TODO Auto-generated method stub
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
nm.cancel(101);
}
}
For local files, do not use Uri.parse(). Use Uri.fromFile(), passing in a File object pointing to the file in question. This should properly escape special characters like #.

Alarm Manager Does Not Execute Repeatedly

I'm working on a group project for a class I'm taking and we cannot seem to figure out why our Alarm Manager does not fire intents repeatedly. We've picked through the source code from top to bottom and cannot seem to isolate the source of this issue.
Can anyone recommend a fix? (or perhaps a starting point?)
// Start service using AlarmManager
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(Rules.this, LMW.class);
PendingIntent pintent = PendingIntent.getService(Rules.this, 0, intent,
0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
7 * 1000, pintent);
// Start 2nd service using AlarmManager
Intent intent2 = new Intent(Rules.this, KillTimer.class);
PendingIntent pintent2 = PendingIntent.getActivity(Rules.this, 0, intent2,
0);
AlarmManager alarm2 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
120 * 1000, pintent2); // here
Source:
public class AlarmManager extends ListActivity {
TextView empty;
TextView empty2;
private static final int ACTIVITY_CREATE = 0;
private static final int ACTIVITY_EDIT = 1;
public static final int INSERT_ID = Menu.FIRST;
private static final int DELETE_ID = Menu.FIRST + 1;
private List<ParseObject> todos;
private Dialog progressDialog;
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
// Override this method to do custom remote calls
public void setVisibility() {
empty.setVisibility(View.VISIBLE);
empty2.setVisibility(View.VISIBLE);
}
protected void doInBackground(Void... params) {
// Gets the current list of todos in sorted order
ParseQuery query = new ParseQuery("TestObject");
query.orderByDescending("_created_at");
try {
todos = query.find();
} catch (ParseException e) {
return;
}
runOnUiThread(new Runnable() {
public void run() {
}});
}
#Override
protected void onPreExecute() {
ToDoListActivity.this.progressDialog = ProgressDialog.show(ToDoListActivity.this, "",
"Loading...", true);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
// Put the list of todos into the list view
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ToDoListActivity.this,
R.layout.todo_row);
for (ParseObject todo : todos) {
adapter.add((String) todo.get("DataI"));
adapter.add((String) todo.get("DataO"));
adapter.add((String) todo.get("DataRSSI"));
adapter.add((String) todo.get("DataSSID"));
adapter.add((String) todo.get("DataTIME"));
adapter.add((String) todo.get("DataRESTRICTED"));
}
setListAdapter(adapter);
ToDoListActivity.this.progressDialog.dismiss();
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_new);
empty = (TextView) findViewById(android.R.id.empty);
empty.setVisibility(View.INVISIBLE);
new RemoteDataTask().execute();
registerForContextMenu(getListView());
}
private void createTodo() {
Intent i = new Intent(this, CreateTodo.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (intent == null) {
return;
}
final Bundle extras = intent.getExtras();
switch (requestCode) {
case ACTIVITY_CREATE:
new RemoteDataTask() {
protected void doInBackground(Void... params) {
String DataI = extras.getString("DataI");
String DataO = extras.getString("DataO");
String DataRSSI = extras.getString("DataRSSI");
String DataSSID = extras.getString("DataSSID");
String DataTIME = extras.getString("DataTIME");
String DataRESTRICTED = extras.getString("DataRESTRICTED");
ParseObject todo = new ParseObject("Todo");
todo.put("DataI", DataI);
todo.put("DataO", DataO);
todo.put("DataRSSI", DataRSSI);
todo.put("DataSSID", DataSSID);
todo.put("DataTIME", DataTIME);
todo.put("DataRESTRICTED", DataRESTRICTED);
try { todo.save(); } catch (ParseException e) {
}
super.doInBackground();
return;
}
}.execute();
break;
case ACTIVITY_EDIT:
// Edit the remote object
final ParseObject todo;
todo = todos.get(extras.getInt("position"));
todo.put("DataI", extras.getString("DataI"));
todo.put("DataO", extras.getString("DataO"));
todo.put("DataRSSI", extras.getString("DataRSSI"));
todo.put("DataSSID", extras.getString("DataSSID"));
todo.put("DataTIME", extras.getString("DataTIME"));
todo.put("DataRESTRICTED", extras.getString("DataRESTRICTED"));
new RemoteDataTask() {
protected void doInBackground(Void... params) {
try {
todo.save();
} catch (ParseException e) {
}
super.doInBackground();
return;
}
}.execute();
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
menu.add(0, INSERT_ID, 0, R.string.menu_insert);
return result;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
// Delete the remote object
final ParseObject todo = todos.get(info.position);
new RemoteDataTask() {
protected void doInBackground(Void... params) {
try {
todo.delete();
} catch (ParseException e) {
}
super.doInBackground();
return;
}
}.execute();
return true;
}
return super.onContextItemSelected(item);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case INSERT_ID:
createTodo();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, CreateTodo.class);
i.putExtra("DataI", todos.get(position).getString("DataI").toString());
i.putExtra("DataO", todos.get(position).getString("DataO").toString());
i.putExtra("DataRSSI", todos.get(position).getString("DataRSSI").toString());
i.putExtra("DataSSID", todos.get(position).getString("DataSSID").toString());
i.putExtra("DataTIME", todos.get(position).getString("DataTIME").toString());
i.putExtra("DataRESTRICTED", todos.get(position).getString("DataRESTRICTED").toString());
i.putExtra("position", position);
startActivityForResult(i, ACTIVITY_EDIT);
}
}
Service Class
public class LMW extends Service {
String Watchdog = "Watchdog";
String Dirty1 = "playboy";
String Dirty2 = "penthouse";
String Dirty3 = "pornhub";
String Dirty4 = "thepiratebay";
String Dirty5 = "vimeo";
String Dirty6 = "wired";
String Dirty7 = "limewire";
String Dirty8 = "whitehouse";
String Dirty9 = "hackaday";
String Dirty10 = "slashdot";
Long mStartRX = TrafficStats.getTotalRxBytes();
Long mStartTX = TrafficStats.getTotalTxBytes();
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "Watchdog Running!", Toast.LENGTH_SHORT).show();
Long.toString(mStartTX);
Long.toString(mStartRX);
ParseObject testObject = new ParseObject("TestObject");
testObject.put("DataO", String.valueOf(mStartTX));
testObject.put("DataI", String.valueOf(mStartRX));
testObject.saveInBackground(); String[] projection = new String[] { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
Cursor cursor = getContentResolver().query(android.provider.Browser.BOOKMARKS_URI,
projection, null, null, null);
String urls = "";
if (cursor.moveToFirst()) {
String url1 = null;
String url2 = null;
do {
String url = cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.URL));
Log.i(Watchdog, url);
if (url.toLowerCase().contains(Dirty1) || url.toLowerCase().contains(Dirty2) || url.toLowerCase().contains(Dirty3) || url.toLowerCase().contains(Dirty4) || url.toLowerCase().contains(Dirty5) || url.toLowerCase().contains(Dirty6) || url.toLowerCase().contains(Dirty7) || url.toLowerCase().contains(Dirty8) || url.toLowerCase().contains(Dirty9) || url.toLowerCase().contains(Dirty10))
{
Intent intent2 = new Intent(LMW.this, Warning.class);
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent2);
break;
} } while (cursor.moveToNext());
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}}
Activity Class:
public class Timer extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.killtimer);
Toast.makeText(getApplicationContext(), "KillWifi Running!", Toast.LENGTH_SHORT).show();
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
int networkId = wifiManager.getConnectionInfo().getNetworkId();
wifiManager.removeNetwork(networkId );
wifiManager.saveConfiguration();
}}
Go through the links, It helped me a lot.
http://android-er.blogspot.in/2010/10/simple-example-of-alarm-service-using.html
http://android-er.blogspot.in/2010/10/schedule-repeating-alarm.html
I have had a similar problem and perhaps it applies to you (hard to tell since the code you supplied is pretty hard to navigate).
My issue was that applying multiple intents to the manager that evaluated as equal overrode the previous applications of that intent. See http://developer.android.com/reference/android/content/Intent.html#filterEquals(android.content.Intent) for what I mean by equivalence.
As an example, I had a schedule that used the URI domy://thing, with extras that varied over each intent (I need to fire the same action with different arguments each time). Extras don't count in equivalence, so my alarms were getting overwritten by each other.
To get around this, I stored a queue of my alarms in a separate file and when one fired, popped the next off the top and put that in the manager. Maybe that'll help you.
UPDATE:
No examples publicly visible, but try this (Trigger is a simple object containing a URI and a time it needs to be fired, scheduleDb is a class that extends SQLiteOpenHelper):
/**
* Pops the next trigger off the queue, adds it to the alarm manager, and
* stores it in the DB in case we need to cancel it later.
*/
private void scheduleNextTrigger() {
Log.d(TAG, "Popping next trigger off queue");
Optional<Trigger> nextTrigger = scheduleDb.getNextTrigger();
if (!nextTrigger.isPresent()) {
Log.d(TAG, "Trigger queue is empty");
return;
}
Trigger trigger = nextTrigger.get();
Log.d(TAG, "Scheduling new trigger " + trigger);
PendingIntent operation = createPendingIntent(trigger);
long timestamp = trigger.getTimestamp();
// Ensure the next item is in the future
if (timestamp > clock.currentTimeMillis()) {
Log.v(TAG, "Found valid trigger: " + trigger);
alarmManager.set(AlarmManager.RTC_WAKEUP, timestamp, operation);
}
scheduleDb.setScheduledTrigger(trigger);
}
private PendingIntent createPendingIntent(Trigger trigger) {
// AlarmManager allows only one instance of each URI, and seems to randomly
// delete bundled URI extras, so we'll encode the triggered URI and place it
// on a constant stem
Uri triggerUri = Uri.parse(TRIGGER_URI + "?" + Uri.encode(trigger.getUri()));
Intent triggerIntent = new Intent(Intent.ACTION_VIEW, triggerUri);
triggerIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Log.d(TAG, "Created trigger intent " + triggerIntent);
PendingIntent operation = PendingIntent.getService(this, 0, triggerIntent, 0);
return operation;
}
Hope that helps

Categories

Resources